【问题标题】:Angular material: How to set required validator as optional in reactive form角度材料:如何以反应形式将所需的验证器设置为可选
【发布时间】:2020-01-10 13:41:10
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

    • 你回答得太快了 :D 5 分钟等待标记答案
    猜你喜欢
    • 2022-11-25
    • 2020-04-26
    • 2020-05-19
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 2018-02-19
    • 2023-02-03
    • 1970-01-01
    相关资源
    最近更新 更多