I have created a reactive form to assign users to a particular role along with validators tp all the fields for the submit button to be active. Now i wanted to disable a few fields upon selection of the user type from the drop-down list in angular

I have provided some code for your reference

this is the .ts file code:

this.form = this._formBuilder.group({
          className: ['', ValidationService.requiredField],
          classTeacherName: ['', ValidationService.requiredField],
          userStatus: ['', ValidationService.requiredField],
          academicYear: ['', ValidationService.requiredField],
          userType: ['', ValidationService.requiredField],
          sectionName: ['', ValidationService.requiredField],
          studentName: ['', ValidationService.requiredField]
        });

there are 4 users to this, they are:

users : string[] = ['student', 'teacher', 'parent', 'admin'];

the expected result is that when the teacher is selected, the validator for classTeacherName should be disabled.

1 Answers

0
Zze On

You can implement your own conditional validation logic by subscribing to form updates and then altering the validators.

setUserCategoryValidators() {
    const classTeacherName = this.form.get('classTeacherName');

    this.form.get('userType').valueChanges
      .subscribe(userType=> {

        if (userType === 'teacher') {
          classTeacherName.setValidators(null);
        }
        else (userType === 'employee') {
          classTeacherName.setValidators([Validators.required]);
        }

        classTeacherName.updateValueAndValidity();
      });
  }

See here for more info on this implementation.