I have several custom form control components in my app so I've implemented a base component that implements the ControlValueAccessor
.
export class BaseControlValueAccessor<T> implements ControlValueAccessor, OnInit {
@Input()
disabled: boolean;
@Input()
required = false;
@Input()
label = '';
@Input()
name = '';
@Input()
placeholder = '';
@Input()
value: T;
constructor(public ngControl: NgControl) {
if (ngControl) {
ngControl.valueAccessor = this;
}
}
public onChange(newVal: T) {}
public onTouched(_?: any) {}
public writeValue(obj: T) {
this.value = obj;
console.log(obj); // <------------
}
public registerOnChange(fn: any) {
this.onChange = fn;
}
public registerOnTouched(fn: any) {
this.onTouched = fn;
}
public setDisabledState?(isDisabled: boolean) {
this.disabled = isDisabled;
}
}
And all of my custom form controls extend this base class. It's all good until here.
In one of the form controls, I needed to replace the original writeValue
method. The problem is that the new writeValue
method is not called but the writeValue
method in the base class gets called.
export class CustomFormControl extends BaseControlValueAccessor<string> {
constructor(
@Self() @Optional() private ngControl: NgControl
) {
super(ngControl);
}
writeValue(value: string) {
this.value = value;
console.log(value); // <- This is not called but the above log is called.
}
}
Did anyone face this issue before? Actually, it seems more related to class inheritance than angular form control, however, I think I've implemented this correctly. Hope to get any help from you.
question from:
https://stackoverflow.com/questions/65895411/writevalue-not-called-angular-custom-form-control 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…