Angular2 Forms 禁用具有数据绑定值的组件中的控件
Angular2 Forms disable control in component with a data-bound value
我在用户不处于编辑模式时禁用控件。
this.theForm = this.builder.group({
name: [{ value: this.model.name, disabled: !this.isEditMode}, Validators.required],
})
当他们更改为编辑模式时,我希望启用该控件。但是,似乎一旦设置它就不会改变,然后组件值就会改变。
当我在标记中加入这个时,它正在工作:
<input [disabled]="!isEditMode" type="text" formControlName="name" />
这导致运行时警告,建议我使用 formControl 处理它。
这是警告:
It looks like you're using the disabled attribute with a reactive form
directive. If you set disabled to true when you set up this control in
your component class, the disabled attribute will actually be set in
the DOM for you. We recommend using this approach to avoid 'changed
after checked' errors.
有没有办法在我设置控件时绑定这个值?
我是否需要循环控制并在它发生变化时切换它?
您可以订阅控件更改并在那里更新它,就像这样(超出我的想象):
ngOnInit() {
for (let nut of this.userSettings.nutrientData) {
this.foodSettingsForm.controls[nut.abbr].valueChanges
.subscribe(v => {
this.completeValueChange(nut.abbr, v, (mode=="edit" ? false : true));
});
}
}
completeValueChange(field: string, value: boolean, disable: boolean) {
this.myForm.controls[myField]
.setValue(({value: vale, disabled: disable}, { onlySelf: true });
}
我在用户不处于编辑模式时禁用控件。
this.theForm = this.builder.group({
name: [{ value: this.model.name, disabled: !this.isEditMode}, Validators.required],
})
当他们更改为编辑模式时,我希望启用该控件。但是,似乎一旦设置它就不会改变,然后组件值就会改变。
当我在标记中加入这个时,它正在工作:
<input [disabled]="!isEditMode" type="text" formControlName="name" />
这导致运行时警告,建议我使用 formControl 处理它。
这是警告:
It looks like you're using the disabled attribute with a reactive form directive. If you set disabled to true when you set up this control in your component class, the disabled attribute will actually be set in the DOM for you. We recommend using this approach to avoid 'changed after checked' errors.
有没有办法在我设置控件时绑定这个值? 我是否需要循环控制并在它发生变化时切换它?
您可以订阅控件更改并在那里更新它,就像这样(超出我的想象):
ngOnInit() {
for (let nut of this.userSettings.nutrientData) {
this.foodSettingsForm.controls[nut.abbr].valueChanges
.subscribe(v => {
this.completeValueChange(nut.abbr, v, (mode=="edit" ? false : true));
});
}
}
completeValueChange(field: string, value: boolean, disable: boolean) {
this.myForm.controls[myField]
.setValue(({value: vale, disabled: disable}, { onlySelf: true });
}