Angular 2:在某些条件下应用 Validator.required 验证 [英] Angular 2: Apply Validator.required validation on some condition

查看:31
本文介绍了Angular 2:在某些条件下应用 Validator.required 验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 angular 2 表单,其中我必须在某些条件下创建一个字段,例如:

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!

推荐答案

您可以根据表单上另一个控件的值添加或删除验证器:

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

这篇关于Angular 2:在某些条件下应用 Validator.required 验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆