I need to apply validators to a specific control in formGroup from outside of a custom control component:
<form [formGroup]="fg">
<custom-control formControlName="custom">
</custom-control>
</form>
this.fg = this.fb.group({
custom: [null,Validator.required]
});
This is the custom control component:
@Component({
selector: 'custom-control',
template: `
<mat-form-field>
<input [formControl]="inputFormControl" />
<mat-error
*ngIf="inputFormControl.hasError('required')">Required</mat-error>
</mat-form-field>
`,
styleUrls: ["custom-control.component.scss"],
providers: [
{
provide: NG_VALUE_ACCESSOR,
multi:true,
useExisting: CustomControlComponent
}
]
})
export class CustomControlComponent implements ControlValueAccessor {
inputFormControl: new FormControl();
onChange = (quantity) => {};
onTouched = () => {};
writeValue(quantity: number) {
this.quantity = quantity;
}
registerOnChange(onChange: any) {
this.onChange = onChange;
}
registerOnTouched(onTouched: any) {}
}
How can I display the required error? and What if I want to set another validator using fg.get('custom').setValidator(XXX)? Thanks!