Angular material:如何以反应形式将必需的验证器设置为可选

Angular material: How to set required validator as optional in reactive form

如何将 required 验证器设置为可选的是反应形式。我有两个输入 amountvolume。如果用户选择 amount 单选按钮,则必须从 volume 输入中删除 必需的验证 。如果 volume,必须从 amount

中删除必需的验证

app.html

  <form #recForm="ngForm" name="form" [formGroup]="form" (ngSubmit)="onSubmit()">
      <div>
        <div class="label">
          <mat-label>Charged by</mat-label>
        </div>
        <mat-radio-group (change)="onChargesType($event)">
          <mat-radio-button
            *ngFor="let charges of chargedBy; let i = index"
            [checked]="i === 0"
            [value]="charges"
            >{{ charges }}</mat-radio-button
          >
        </mat-radio-group>
      </div>

      <mat-form-field *ngIf="!isAmount">
        <input formControlName="volume" matInput placeholder="Volume" />
      </mat-form-field>
      <mat-form-field *ngIf="isAmount">
        <input formControlName="amount" matInput placeholder="Amount" />
      </mat-form-field>
  </form>

app.ts

chargedBy: string[] = ['amount', 'volume'];

  ngOnInit() {
    this.isChargedByAmount = true;
    this.form = this.fb.group({
      volume: ['', []],
      amount: ['', []],
    });
  }

  onChargesType(event: MatRadioChange) {
    if (event.value === 'amount') {
      this.form.get('amount').setValidators(Validators.required);
      this.form.get('volume').clearValidators();
      this.isChargedByAmount = true;
    }

    if (event.value === 'volume') {
      this.form.get('volume').setValidators(Validators.required);
      this.form.get('amount').clearValidators();
      this.isChargedByAmount = false;
    }
  }

我认为这是因为你必须调用方法 updateValueAndValidity() 当您在 运行 时添加或删除验证器时,您必须调用 updateValueAndValidity() 以使新验证生效。

我从官方 angular 文档中找到这个 https://angular.io/api/forms/AbstractControl#clearValidators