How to add required asterisk in a custom control?

0

Issue

I’m using angular 6 to create a custom component which contains a custom form control. So far, I’ve implemented ControlValueAccessor in my component.

My custom control is a simple MatSelect component from Angular Material. I want to show the asterisk (*) for when that control is required.

So far, I’ve got the custom control to work, but adding the required attribute to the component doesn’t add the asterisk to my control!

<app-provinces formControlName="projectProvince" required></app-provinces>

Should I define an @Input variable for it and handle it manually, or should it be done automatically?

Solution

Yes you should add a required @Input() to your component.

Something like this:

<div class="form-group m-form__group row" [ngClass]="{
                    'has-danger': formGroup.controls[formControlName].invalid && formGroup.controls[formControlName].touched,
                    'has-success': formGroup.controls[formControlName].valid && formGroup.controls[formControlName].touched,
                    'has-no-action': formGroup.controls[formControlName].untouched
                                }">
        <label class="col-form-label col-lg-3 col-sm-12" [for]="formControlId">
            {{formControlLabel}}
            <span *ngIf="isRequired" class="required" aria-required="true"> * </span>
        </label>
        <div class="col-lg-4 col-md-9 col-sm-12">
            <select placeholder="place_holder_text" [disabled]="disabled" [class]="formControlName" [id]="formControlId" [data]="formControlItems"  (click)="setAsTouched()" (valueChanged)="store($event)"></select>
            <div class="form-control-feedback">{{formControlErrorText || 'Required Field May Not Be Empty'}}</div>
            <span class="m-form__help">{{formControlHelpText}}</span>
        </div>
    </div>

Component:

@Input('required') isRequired: boolean;

Example usage:

<select-form-control
    [required]="true"
    [group]="myFormGroup"
    label="Name"
    name="name"
    controlId="name"
    [inputItems]="array"
    helpText="Enter..."
    [value]="name"
    (valueChange)="someMethod($event)">
</select-form-control>

Answered By – Fateme Fazli

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More