我遇到了使用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中的传入值。 –