How to add required asterisk in a custom control?
How to add required asterisk in a custom control?
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.
ControlValueAccessor
My custom control is a simple MatSelect
component from Angular Material. I want to show the asterisk (*
) for when that control is required.
MatSelect
*
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!
required
<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?
@Input
Well, I assume it is a form control as another ones !
– Mohammad Dayyan
Jul 1 at 10:34
1 Answer
1
Yes you should add a required
@Input()
to your component.
required
@Input()
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>
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
I'm confused. Why would an asterisk magically appear where you want it to appear if you have not added any code in your component to do that?
– JB Nizet
Jul 1 at 10:19