Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2: Apply Validator.required validation on some condition

I have a angular 2 form wherein I have to make a field required on some condition like:

description:  ['', Validators.required]

This description field will be required only on some type of a condition like:

if(true){descReq = true};

How can I achieve this, please suggest. Thanks in advance!

like image 628
Abhishek Avatar asked Feb 15 '17 00:02

Abhishek


1 Answers

You can add or remove a validator based on the the value of another control on the form:

    testForm: FormGroup;

    constructor(private formBuilder: FormBuilder) {
      this.testForm = this.formBuilder.group({
        condition: [''],
        description: ['']
      });

      this.testForm.controls['condition'].valueChanges.subscribe(result => {
        if (result) {
          this.testForm.controls['description'].setValidators(Validators.required);
          this.testForm.controls['description'].updateValueAndValidity();
        } else {
          this.testForm.controls['description'].setValidators(null);
          this.testForm.controls['description'].updateValueAndValidity();
        }
      });
    }
like image 140
JayChase Avatar answered Sep 22 '22 00:09

JayChase