【问题标题】:Angular reactive form - Disable material design buttons in FormGroup角度反应形式 - 禁用 FormGroup 中的材料设计按钮
【发布时间】:2019-12-25 14:32:11
【问题描述】:

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

我尝试在构造函数和 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(),表单中的按钮也会被禁用。

按钮在初始化期间没有被禁用是一个错误还是我做错了什么?如何在初始化时在 UI 中禁用按钮?

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

1当我问这个问题时,我对 Angular 的 resolve guard 不熟悉,它可用于在导航到组件之前加载动态数据。

【问题讨论】:

  • 你能确保你提供的 stackblitz 工作正常吗?对我来说,它显示未找到.. 希望这 stackblitz.com/edit/… 有帮助..
  • 感谢您的关注。请立即重试

标签: angular angular-material2 angular-reactive-forms


【解决方案1】:

您不应该对按钮使用表单控件。只需禁用表单并使用按钮禁用,例如:

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

Stackblitz

【讨论】:

    猜你喜欢
    • 2022-11-25
    • 1970-01-01
    • 2020-05-19
    • 1970-01-01
    • 2021-09-14
    • 2023-03-20
    • 1970-01-01
    • 2015-10-16
    • 2015-07-28
    相关资源
    最近更新 更多