我目前正在使用自定义表单字段控件开发可重用组件。
我有这个自定义的自动完成控件,它返回一个对象作为它的值,然后我的可重用组件使用这个自定义控件将对象属性之一作为字符串传递给我的主窗体。这是一个闪电战来检查它:
https://stackblitz.com/edit/my-custom-autocomplete-jlkj9q
这在一个方向上工作正常,控制-> 可重用字段-> 表单。
以下是我从可重用组件更新表单值的方法:
ngOnInit(){
this.state = new FormControl(null);
// any time the form field value changes update the parent of any change
this.state.valueChanges
.pipe(takeUntil(this._destroy))
.subscribe(value => {
if(!!value && !!value.name){
this.onChange(value.name) //pass only the state.name to the ControlValueAccessor
this.onTouched();
}
else{
this.onChange(value)
this.onTouched();
}
});
}
现在,当我为可重用组件字段设置默认值时,控件会正确更新,但表单值不会。我尝试使用要传递给主窗体的值调用该onChange()方法,但什么也没发生。ngOnInit然后我尝试在 ngAfterViewInit 上设置默认值并onChange像这样调用:
ngAfterViewInit(){
let defaultValue = {
"name": "Arkansas",
"population": "2.978M",
"flag": "https://upload.wikimedia.org/wikipedia/commons/9/9d/Flag_of_Arkansas.svg"
};
this.state.setValue(defaultValue);
this.onChange(defaultValue);
}
但这也不起作用。
我在这里想念什么?有什么线索吗?