【发布时间】:2021-03-11 08:49:30
【问题描述】:
我正在使用 Angular 11 和带有表单组的表单。我的表单中有几个字段,我想根据外部情况设置启用/禁用。这适用于预期的输入字段。
我在stack blitz上做了一个简单的例子:https://stackblitz.com/edit/my-cb-test?file=src/app/app.component.html
我做了什么,我有我的 app-component.ts:
import { Component, VERSION } from "@angular/core";
import { FormGroup, FormBuilder, Validators } from "@angular/forms";
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
name = "Angular " + VERSION.major;
bvalue = true;
disbled = false;
form: FormGroup;
constructor(private fb: FormBuilder) {
this.buildFormGroup(this.disbled);
}
buildFormGroup(dis: boolean): void {
this.form = this.fb.group({
firstCB: [
{ value: this.bvalue, disabled: dis },
[Validators.requiredTrue]
],
inputField: [{ value: "Test", disabled: dis }, [Validators.required]]
});
}
switch(): void {
this.disbled = !this.disbled;
console.log("Disabled: " + this.disbled);
this.buildFormGroup(this.disbled);
}
}
还有我的html:
<form [formGroup]="form">
<div>
<mat-checkbox formControlName="firstCB">
Checkbox
</mat-checkbox>
</div>
<mat-form-field>
<input matInput formControlName="inputField" type="text" />
</mat-form-field>
<button (click)="switch()">Click</button>
</form>
当我单击按钮时,输入字段按预期启用/禁用,但复选框保持启用状态(或更准确地说是它具有的第一个状态)。
知道这里有什么问题吗?
编辑:我知道我可以在 HTML 中使用 [disabled]="condition" 但这被认为是不好的做法并在控制台中发出警告...
【问题讨论】:
-
这能回答你的问题吗? Angular [disabled]="MyBoolean" not working
-
您也可以尝试在 input 和 mat-checkbox 标签中使用 [disabled]="disbled"
-
我使用此解决方法来禁用字段,但它在浏览器控制台中发出警告“看起来您正在使用带有反应表单指令的 disabled 属性。如果您在您设置 disabled 为 true 时在你的组件类中设置这个控件,disabled 属性实际上会在 DOM 中为你设置。我们建议使用这种方法来避免“检查后更改”错误。”所以显然这不是反应形式的预期方式。
标签: angular typescript angular-forms