2017-03-31 19 views
1

我寫我自己的自定義表單元素DateInputComponent通過實施ControlValueAccessor和使用它像這樣:如何訪問NgFormControl定製NG2表單元素

<my-date-input ngControl="date"></my-date-input> 

從我個人理解,ngControl[ngFormControl]="myControlGroup.controls['date']"語法糖。

現在,在我的DateInputComponent裏我想訪問NgFormControl

我試圖將它與@Input NgFormControl ngFormControl;綁定,但它永遠不會被設置,我試圖用DateInputComponent(NgFormControl ngFormControl)注入它,但由於沒有提供程序而失敗。

什麼是正確的方法來得到它?

(也許我也快到了錯誤的方式...我想這DateInputComponent能夠通過自身來顯示所有驗證錯誤可能發生。)

+0

'ngFormControl'從哪裏來? – yurzui

+0

正如我所說,根據我的理解,'ngControl =「date」'是用於分配此屬性的語法糖。 – enyo

回答

1

this comment提示:通過注入Injector和讀取NgControl出來的:

class DateInputComponent implements ControlValueAccessor, AfterViewInit { 
    Injector _injector; 
    DateInputComponent(this._injector); 

    NgControl control; 

    @override 
    ngAfterViewInit() { 
    control = _injector.get(NgControl).control; 
    } 
} 

直接注入NgControl,特德建議,是不行的,因爲它會導致循環依賴。

試圖在構造函數中訪問NgControl將無法​​使用,因爲它尚不可用。

1

你在正確的方法注入指令,但問題是,雖然ngControl可能被認爲是NgFormControl的語法糖,但它不是同一類。

所有窗體控件都是從NgControl擴展而來的,這就是你應該注入到組件中的東西。 DateInputComponent(NgControl ngControl)

所有的表單指令都可以互換使用,因此它們都提供了NgControl作爲他們所暴露的接口。這使您的日期組件的用戶使用任何指令,其使用情況下的工作原理:

  • NgModel:如果他們只是想提供或收聽值
  • NgFormControl:如果他們想提供控制
  • NgControlName:如果他們想使用字符串標識到ControlMap(這是你在上面使用的)我得到了它與解決方案合作
+0

謝謝。但是當我嘗試添加'DateInputComponent(NgControl ngControl)'我的應用程序不再編譯時,說:'不能實例化循環依賴! NgControlName ' – enyo

+0

這是我們使用的一種常見模式,因此它應該是可能的。你可以在這裏看到一個例子:https://github.com/dart-lang/angular_components/blob/master/lib/src/components/material_radio/material_radio.dart#L65 你絕對不應該需要使用噴油器。如果我在代碼中看到這是一種代碼味道。 –