[英]Can I access to formControl of my custom ControlValueAccessor in Angular 2+?
[英]Custom ControlValueAccessor doesn't seem to work for my own FormControl directive
我正在嘗試實現此答案,因為我一直在嘗試創建自己的自定義FormControl
如該問題中所述)。
我創建了一個自定義ControlValueAccessor
並將其作為valueAccessor
注入到FormControl
指令的構造函數中,但是當我嘗試使用registerOnChange
函數注冊回調時,它永遠不會被調用。
實際上,似乎沒有成員被召集。
我已經閱讀了許多文章和博客文章,但無法弄清我所缺少或做錯的地方。
任何幫助或指針,將不勝感激。
目標就像另一個問題一樣,可以執行@Component({..., template: '<input myFormControl...'}...
來注冊FormControl。
您幾乎在那里:)。 不過,還有另外一招。
您的自定義NgControl
不會調用setUpControl
該函數被調用內部ngOnChanges
的FormControlDirective
。 這是因為您的自定義控件的@Inputs
未被更改。 此外,您不會在控件上使用任何輸入。
但是您可以手動運行它:
import { SimpleChange } from '@angular/core';
export class HybridFormControlDirective extends FormControlDirective {
/* @override */
constructor(...) {
super(validators, asyncValidators, valueAccessors);
this.form = new FormControl('');
this.form.patchValue('test2');
// manually call ngOnChanges to make sure that setUpControl is called
this.ngOnChanges({
form: new SimpleChange(undefined, this.form, true)
});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.