角反应形式-在FormGroup中禁用材料设计按钮

问题描述 投票:0回答:1

我有一个包含Angular材质设计组件的反应形式。我想在初始化组件时禁用表单中的所有控件。

我已经尝试在构造函数中以及ngOnInit()中的FormGroup上调用disable(),但是由于某些原因,表单中的按钮(使用材质设计)仍然处于启用状态。

Stackblitz

模板:

<form [formGroup]="emailForm">
  <mat-form-field>
    <input matInput type="email" formControlName="email" placeholder="Email" />
  </mat-form-field>
  <button formControlName="removeButton" mat-icon-button class="button-small" (click)="clearEmail()" matTooltip="Clear email address" matTooltipClass="tooltip-medium" [matTooltipShowDelay]="500" ngDefaultControl>
    <mat-icon aria-label="Clear">clear</mat-icon>
  </button>
</form>

组件:

export class EmailFormComponent implements OnInit {
  private emailForm: FormGroup;

  constructor(private formbBuilder: FormBuilder) {
    this.createReactiveForm();
  }

  ngOnInit() {
     this.emailForm.disable();
  }  

  createReactiveForm() {
    this.emailForm  = this.formbBuilder.group({
      email: ['', [Validators.email, Validators.maxLength(100)]],
      removeButton : ['']
    });

    this.emailForm.disable();
  }

  clearEmail() {
    this.emailForm.patchValue({email:''});
  }
}

如果我从按钮中删除材料设计,它将在初始化期间被禁用。如果我从组件中的click eventHandler方法调用this.emailform.disable(),则表单中的按钮也会被禁用。

是在初始化期间未禁用按钮的错误,还是我做错了什么?如何在初始化时在用户界面中禁用按钮?

((注:这是一个简化的示例。实际的应用程序在表单中具有更多输入字段)。

angular angular-material2 angular-reactive-forms
1个回答
1
投票

您不应该将表单控件用于按钮。只需禁用表单并使用按钮禁用即可:

<button [disabled]="emailForm.disabled" ...

Stackblitz

© www.soinside.com 2019 - 2024. All rights reserved.