英文:
Disabled attribute with a reactive form directive button
问题
我有一个这样的表单:
<div [formGroup]="form">
<input type="text" formControlName="lastName" id="lastName" name="lastnamefield" />
<input type="text" formControlName="firstName" id="firstName" name="firstnamefield" />
<button pButton id="searchButton" [disabled]="isDone" (click)="handleClick()"></button>
</div>
这是我创建表单的方式:
form = this.formbuilder.group({
lastName: [{ value: undefined, disabled: false }, Validators.required],
firstName: [{ value: undefined, disabled: false }],
});
我使用 handleClick()
来执行一些操作,然后将按钮和输入框设置为禁用,如下所示:
private handleClick(){
// 执行一些操作...
isDone = true;
this.form.get('firstName')?.disable();
this.form.get('lastName')?.disable();
}
我在控制台中收到一个警告:
看起来您正在使用带有响应式表单指令的 disabled 属性。如果您在组件类中设置 disabled 为 true,那么 disabled 属性实际上会在 DOM 中为您设置。我们建议使用这种方法以避免“变更检测后已更改”错误。
我尝试将 [formcontrolname]
添加到按钮上,但显然不可能。在这种情况下,我应该怎么做,还是可以忽略警告?
英文:
I have a form like this:
<div [formGroup]="form">
<input type="text" formControlName="lastName" id="lastName"
name="lastnamefield" />
<input type="text" formControlName="firstName" id="firstName"
name="firstnamefield" />
<button pButton id="searchButton" [disabled]="isDone" (click)="handleClick()"></button>
</div>
This is how I create the form:
form = this.formbuilder.group({
lastName: [{ value: undefined, disabled: false }, Validators.required],
firstName: [{ value: undefined, disabled: false }],
});
I use the handleClick()
to do some operations and then set the button and inputs to disabled like this:
private handleClick(){
// do some operations...
isDone = true;
this.form.get('firstName')?.disable();
this.form.get('lastName')?.disable();
}
I get a warning in the console:
> 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.
I tried adding the [formcontrolname]
to the button, but apparently it is not possible. What should I do in this case or should I just ignore the warning?
答案1
得分: 0
使用这个替代:
form = this.formbuilder.group({
lastName: [{ value: undefined, disabled: true }, Validators.required],
firstNames: [{ value: undefined, disabled: true }],
});
英文:
use this instead:
form = this.formbuilder.group({
lastName: [{ value: undefined, disabled: true }, Validators.required],
firstNames: [{ value: undefined, disabled: true }],
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论