Ralph Ritoch
Ralph Ritoch

Reputation: 3440

Conditional field validation in Angular 6+ depending on value of select field

I'm trying to do optional fields which are only required for certain values of a select box. I thought I was close but the value isn't populated at the time of validation.

requiredForTypeValidator = 
    (values) => 
        (control: any): {[key: string]: boolean} | null => {

    const ticket_type = control.parent ? control.parent.value.type : '';
    if (control.value !== undefined && ((control.value === null || control.value.length < 1) && values.indexOf(ticket_type) !== -1)) {
        return {'required': true};
    }
    return null;
}

 ngOnInit() {
    this.createTicketForm = this.formBuilder.group({
        type: [null, Validators.required],
        optField: [null, this.requiredForTypeValidator(['validate_me','validate_me_too'])],
    });
 }

By request I have recreated this problem at stackblitz: https://stackblitz.com/edit/angular-nt8hjw

Upvotes: 0

Views: 1298

Answers (1)

jakubm
jakubm

Reputation: 422

Here you have working solution for you problem stackblitz .

Basically I create new function which subscribes to the dropdown changes and updates validators for dependent field.

private setValidators(): void {
    this.createTicketForm.get('type').valueChanges.subscribe(
    (result) => {
      if ( result ==='Check me') {
        this.createTicketForm.get('optField').setValidators(Validators.required);
        console.log('validator set');
      } else {
        this.createTicketForm.get('optField').setValidators(null);
      }
      this.createTicketForm.get('optField').updateValueAndValidity();
    }
   );
}

Upvotes: 1

Related Questions