angular - 在复选框/单选按钮上禁用 Angular 11 表单
问题描述
我正在使用 Angular 11 和带有表单组的表单。我的表单中有几个字段,我想根据外部情况设置启用/禁用。这适用于预期的输入字段。
我在堆栈闪电战上做了一个简单的例子: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" 但这被认为是不好的做法并在控制台中发出警告......
解决方案
我没有时间深入研究 MatCheckbox 代码,但它似乎对重新分配 FormControl 绑定没有反应。如果您尝试重新使用相同的表单(和表单控件)并简单地启用/禁用整个表单(或特定的 FormControl),您会看到它被正确禁用。不确定这是否是您可以接受的解决方法。
尝试在 angular material repo 中提交错误报告(或查看代码 - 也许它按预期工作)。
Adn 关于您问题下的评论 - 您不应将disabled
属性与反应式表单绑定混合。这是一种不好的做法,并且会在您为开发中的应用程序提供服务时引发警告(并且可能还会导致其他问题,具体取决于您的用例)。
推荐阅读
- vue.js - VUE中如何将表单值转换为数组
- algorithm - 这个优化算法的正式名称?
- java - 使用数组列表在java中写入文件但不工作
- json - 使用 jq 从 json 获取父值
- android - 在 AndroidStudio 3.1.4 中,CoordinatorLayout 不显示 targetSdkVersion 28
- r - 在 R 中重塑 data.frame
- reactjs - 允许在 npm 模块中直接导入文件,如 lodash
- python - python服务器完成但没有监听
- talend - Talend - 无法从 tsendmail 发送邮件
- google-apps-script - 将谷歌表格中的单元格设置为只读而不锁定其列宽?