Angular 2: Apply Validator.required validation on some condition

前端 未结 4 666
轮回少年
轮回少年 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-16 05:49

    You should set the validator on the field imperatively vs declaratively.

    Declaratively (your current code):

    const description = new FormControl('', Validators.required);
    

    Imperatively:

    const description = new FormControl('');
    if (someCondition) {
      description.setValidators(Validators.required);
    }
    

提交回复
热议问题