Angular 2: Apply Validator.required validation on some condition

前端 未结 4 667
轮回少年
轮回少年 2020-12-16 05:09

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

description:  [\'\', Validators.required]

This desc

4条回答
  •  孤城傲影
    2020-12-16 06:03

    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();
            }
          });
        }
    

提交回复
热议问题