首页 > 解决方案 > 在复选框/单选按钮上禁用 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" 但这被认为是不好的做法并在控制台中发出警告......

标签: angulartypescriptangular-forms

解决方案


我没有时间深入研究 MatCheckbox 代码,但它似乎对重新分配 FormControl 绑定没有反应。如果您尝试重新使用相同的表单(和表单控件)并简单地启用/禁用整个表单(或特定的 FormControl),您会看到它被正确禁用。不确定这是否是您可以接受的解决方法。

这是更新的 stackblitz

尝试在 angular material repo 中提交错误报告(或查看代码 - 也许它按预期工作)。

Adn 关于您问题下的评论 - 您不应将disabled属性与反应式表单绑定混合。这是一种不好的做法,并且会在您为开发中的应用程序提供服务时引发警告(并且可能还会导致其他问题,具体取决于您的用例)。


推荐阅读