反应形式-禁用的属性 [英] Reactive forms - disabled attribute
问题描述
我正在尝试使用formControl
中的disabled
属性.当我将其放在模板中时,它会起作用:
I am trying to use the disabled
attribute from a formControl
. When I put it in the template, it works:
<md-input formControlName="id" placeholder="ID" [disabled]="true"></md-input>
但是浏览器会提醒我:
您似乎正在使用带有反应形式的Disabled属性 指示.如果将禁用设置为true 当您在组件类中设置此控件时,disabled属性实际上将在DOM中设置为 你.我们建议使用这种方法来避免检查后更改"错误.
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.
Example:
form = new FormGroup({
first: new FormControl({value: 'Nancy', disabled: true}, Validators.required),
last: new FormControl('Drew', Validators.required)
});
所以我将其放在FormControl
中,并从模板中删除:
So I put it in the FormControl
, and deleted from the template:
constructor(private itemsService: ItemsService) {
this._items = [];
this.myForm = new FormGroup({
id: new FormControl({value: '', disabled: true}, Validators.required),
title: new FormControl(),
description: new FormControl()
});
this.id = this.myForm.controls['id'];
this.title = this.myForm.controls['title'];
this.description = this.myForm.controls['description'];
this.id.patchValue(this._items.length);
}
但是它不起作用(它没有禁用input
).有什么问题吗?
But it does not work (it is not disabling the input
). What is the problem?
推荐答案
我一直在使用[attr.disabled]
,因为与高级IMO相比,我仍然喜欢此模板而不是程序化enable()/disable()驱动.
I have been using [attr.disabled]
because I still like this template driven than programmatic enable()/disable() as it is superior IMO.
更改
<md-input formControlName="id" placeholder="ID" [disabled]="true"></md-input>
到
<md-input formControlName="id" placeholder="ID" [attr.disabled]="true"></md-input>
如果您使用的是较新的资料,请将md-input
更改为mat-input
.
If you are on newer material change md-input
to mat-input
.
这篇关于反应形式-禁用的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!