angularangular-materialangular-reactive-formsangular-validator

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


How to set required validator as optional is reactive form. I've two inputs amount and volume. if user choose amount radio button, required validation must be removed from volume input. If volume, required validation must removed from 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;
    }
  }


Solution

  • I think it is because you must call method updateValueAndValidity() When you add or remove a validator at run time, you must call updateValueAndValidity() for the new validation to take effect.

    I find this from official angular doc https://angular.io/api/forms/AbstractControl#clearValidators