3

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

应用程序.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>

应用程序.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;
    }
  }

4

1 回答 1

5

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

我从官方角度文档https://angular.io/api/forms/AbstractControl#clearValidators

于 2020-01-10T13:43:44.410 回答