javascripthtmlangularionic-frameworkangular-custom-validators

setValidators doesn't work at all when set dynamically inside of a function


I am not sure why setValidators is not working in my below code. I am not sure what the issue is as it doesn't take any effect when I set the formControl as required. What I want to achieve is to dynamically set some FormControls required if a specific option is selected. If you have any idea that would be amazing. Thank you!

This is my HTML

 <form [formGroup]="measurementsForm">
    <ion-grid>
      <ion-row>
        <ion-col>
        <ion-row class="quiz-choices">
            <ion-col>
              <ion-select
                [interfaceOptions]="customInterfaceOptions"
                formControlName="weightMeasurement"
                interface="action-sheet"
                placeholder="weight">
                <ion-select-option value="kg">kg</ion-select-option>
                <ion-select-option value="lbs">lbs</ion-select-option>
              </ion-select>
            </ion-col>

            <ion-col>
              <ion-input
                inputmode="numeric"
                formControlName="weightAmount"
                placeholder="Weight"
                value="amount">
              </ion-input>
            </ion-col>
          </ion-row>

          <ion-row>
            <ion-col>
              <ion-select
                [interfaceOptions]="customInterfaceOptions"
                formControlName="heightMeasurement"
                interface="action-sheet"
                placeholder="height"
                (ionChange)="onSelectFootMeasurement($event)">
                <ion-select-option value="cm">cm</ion-select-option>
                <ion-select-option value="ft">ft</ion-select-option>
              </ion-select>
            </ion-col>

            <ion-col *ngIf="!showFtInput">
              <ion-input
                inputmode="numeric"
                formControlName="heightAmountCm"
                placeholder="amount">
              </ion-input>
            </ion-col>
            <ion-col *ngIf="showFtInput">
              <ion-input
                formControlName="heightAmountFoot"
                placeholder="foot"
                inputmode="numeric">
              </ion-input>
            </ion-col>
            <ion-col *ngIf="showFtInput">
              <ion-input
                formControlName="heightAmountInch"
                placeholder="inch"
                inputmode="numeric">
              </ion-input>
            </ion-col>
          </ion-row>
        </ion-col>
      </ion-row>
    </ion-grid>
  </form>

This is my TS

import { Component, OnInit } from "@angular/core";
import { FormGroup, FormControl, Validators } from "@angular/forms";
import { NavController } from "@ionic/angular";

@Component({
  selector: "app-step-two",
  templateUrl: "./step-two.page.html",
  styleUrls: ["./step-two.page.scss"],
})
export class StepTwoPage implements OnInit {
  customInterfaceOptions: any = {
    cssClass: "alertCustomCss",
  };
  measurementsForm: FormGroup;

  selectedHeightMeasurement = "";
  showFtInput = false;

  constructor(private navCtrl: NavController) {}

  ngOnInit() {
    this.measurementsForm = new FormGroup({
      weightMeasurement: new FormControl(null, {
        validators: [Validators.required],
      }),
      weightAmount: new FormControl(null, {
        validators: [Validators.required],
      }),
      heightMeasurement: new FormControl(null, {
        validators: [Validators.required],
      }),
      heightAmountCm: new FormControl(),
      heightAmountFoot: new FormControl(),
      heightAmountInch: new FormControl(),
    });
  }

  onSelectFootMeasurement(event) {
    this.selectedHeightMeasurement = event.detail.value;
    if (this.selectedHeightMeasurement === "ft") {
      this.showFtInput = true;
      this.measurementsForm
        .get("heightAmountFoot")
        .setValidators([Validators.required]);
      this.measurementsForm
        .get("heightAmountInch")
        .setValidators([Validators.required]);
    } else if (this.selectedHeightMeasurement === "cm") {
      this.measurementsForm
        .get("heightAmountCm")
        .setValidators([Validators.required]);
      this.showFtInput = false;
    }
  }

}

Solution

  • You need to updateValueAndValidity

    dynamicValidation(): void {
        let control1 = null;
        control1 = this.measurementsForm.get('controlName');
          control1.setValidators([Validators.pattern(this.nameREGEX), Validators.minLength(this.minLength)]);
      control1.updateValueAndValidity();
    
      }