我的应用程序中有几个自定义表单控件组件,因此我实现了一个基本组件,它实现了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;
}
}
我所有的自定义表单控件都扩展了这个基类。到这里为止一切都很好。
在其中一个表单控件中,我需要替换原始writeValue
方法。问题是writeValue
没有调用新方法,而是调用writeValue
了基类中的方法。
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.
}
}
以前有人遇到过这个问题吗?实际上,它似乎与类继承比角度形式控制更相关,但是,我认为我已经正确地实现了这一点。希望能得到你的任何帮助。