我遇到了使用Angular 2 ngModel綁定的問題。 plnkrngModel綁定在Angular 2的OnInit中爲null
如果我使用ngModel將值綁定到子組件,則該值不會填充到子組件的OnInit函數中。所以如果我綁定到一個屬性調用「boundName」,我嘗試訪問OnInit中的它,它將爲空。但是,如果我綁定到父控件中不使用ngModel但輸入參數相同的值,可以在OnInit函數中訪問該值。
所以..如果我的父母組件創建像
<my-boundcomp [(ngModel)]="name" [(inputName)] ="name" ></my-boundcomp>
子組件和我的子組件的OnInit功能是
public ngOnInit() {
console.log("Input Name :" + this.inputName);
console.log("Bound Name :" + this.boundName);
this._boundNameOnInit = this.boundName; // <--- Going to be null
this._inputNameOnInit = this.inputName; // <--- Going to be not null
}
我發現這種行爲是奇數,並意外。我不確定這是一個錯誤還是我沒有正確使用FormsModule ngModel,但足夠有趣,我想我應該分享。
以下是完整的plnkr https://plnkr.co/edit/Im5oz7q1HhG5MgGTTZ1R?p=preview
如果是這樣的話,那麼我會訪問nginitode的oninit獲取值?這給了我相同的結果(https://plnkr.co/edit/POWoAgw8kYJToPhJwWQw?p=preview)。 –
我不認爲你可以影響。你可以爲你的組件添加一個'@Input()ngModel;',但可能有其他不需要的副作用。 –
我同意..我的觀點是,我仍然認爲這裏有些不太對勁。我不確定這是否按設計工作,爲什麼你不能訪問OnInit中的傳入值。 –