![](/img/trans.png)
[英]How can I trigger custom and built in validators to validate on an ng2 template form?
[英]How to access NgFormControl in custom Ng2 form element
我通過實現ControlValueAccessor
編寫了自己的自定義表單元素DateInputComponent
,並像這樣使用它:
<my-date-input ngControl="date"></my-date-input>
據我了解, ngControl
是[ngFormControl]="myControlGroup.controls['date']"
語法糖。
現在,在我的DateInputComponent
內部,我想訪問NgFormControl
。
我試圖將其與@Input NgFormControl ngFormControl;
綁定@Input NgFormControl ngFormControl;
但它從未設置過,我嘗試用DateInputComponent(NgFormControl ngFormControl)
注入它,但是失敗了,因為沒有提供者。
什么是正確的方法呢?
(也許我也以錯誤的方式來處理它……我希望此DateInputComponent
能夠單獨顯示可能發生的所有驗證錯誤。)
您可以使用正確的方法插入指令,但是問題是,雖然ngControl
可以被視為NgFormControl的語法糖,但它不是同一類。
所有窗體控件都從NgControl擴展而來,這就是您應該注入到組件中的內容。 DateInputComponent(NgControl ngControl)
所有的形式指令都是可以互換使用的,因此它們都提供NgControl作為公開的接口。 這允許您的日期組件的用戶使用適用於其用例的任何指令:
NgModel
:如果他們只是想提供或收聽值 NgFormControl
:如果他們想提供控件 NgControlName
:如果他們想在ControlMap中使用字符串標識符(這是您在上面使用的字符串) 我將它與此注釋建議的解決方案一起使用:通過注入Injector
並NgControl
讀取NgControl
:
class DateInputComponent implements ControlValueAccessor, AfterViewInit {
Injector _injector;
DateInputComponent(this._injector);
NgControl control;
@override
ngAfterViewInit() {
control = _injector.get(NgControl).control;
}
}
正如Ted所建議的NgControl
,直接注入NgControl
不起作用,因為這會導致循環依賴性。
嘗試在構造函數中訪問NgControl
無效,因為尚不可用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.