角材料:如何以反应形式将所需的验证器设置为可选

时间:2020-01-10 13:41:10

标签: angular angular-material angular-reactive-forms angular-validator

如何将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;
    }
  }

1 个答案:

答案 0 :(得分:5)

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

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