I’ve created a component (AComponent) which uses Material design and I would like to use it as formControl in my Reactive Form (in the AppComponent).
I’ve implemented ControlValueAccessor in this component (AComponent).
export class AComponent implements ControlValueAccessor {
fm = new FormControl();
constructor(private ngControl: NgControl) {
ngControl.valueAccessor = this;
this.fm.valueChanges.subscribe(v => {
this.onChange(v);
})
}
onChange = (_: any) => {}
onTouched = () => {}
writeValue(obj: any) {
this.fm.setValue(obj);
}
registerOnChange(fn: any) {
this.onChange = fn;
}
registerOnTouched(fn: any) {
this.onTouched = fn;
}
}
I can set Validators.required for this component (in the AppComponent)
ngOnInit() {
this.formGroup = this.fb.group({
control: ['', Validators.required],
controlOne: ['', Validators.required]
})
this.formGroup.statusChanges
.subscribe(console.log);
}
and it affects the whole form. (you can see on the console: invalid when ACompnent is invalid).
But the problem is I cannot force AComponent to look like invalid (red input) in case when it is invalid.
It looks like inner formControl (in the AComponent) doesn’t get Validators.required from AppComponent.
The question is: How can I set validators to AComponent in an elegant way?
