Angular如何在创建控件后将验证器添加到FormControl? [英] Angular How to add Validator to FormControl after control is created?

查看:1090
本文介绍了Angular如何在创建控件后将验证器添加到FormControl?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个拥有动态构建表单的组件。用验证器添加控件的代码可能如下所示:

  var c = new FormControl('',Validators.required); 

但是让我们假设我想稍后添加第二个验证器 。我们怎样才能做到这一点?我们无法在网上找到任何文件。我确实发现,尽管在表单控件中有setValidators

  this.form.controls [firstName]。setValidators 

但不清楚如何添加新的或自定义的验证器。



感谢大家。

解决方案

验证器数组。



以下示例显示如何将验证程序添加到现有的FormControl中:

  this.form.controls [firstName]。setValidators([Validators.minLength(1),Validators.maxLength(30)]); 

请注意,这将重置您在创建FormControl时添加的任何现有验证器。

We have a component that has a dynamically built form. The code to add a control with validators might look like this

var c = new FormControl('', Validators.required);

But let's say that I want to add 2nd Validator later. How can we accomplish this? We cannot find any documentation on this online. I did find though in the form controls there is setValidators

this.form.controls["firstName"].setValidators 

but it is not clear how to add a new or custom validator.

Thanks a bunch.

解决方案

You simply pass the FormControl an array of validators.

Here's an example showing how you can add validators to an existing FormControl:

this.form.controls["firstName"].setValidators([Validators.minLength(1), Validators.maxLength(30)]);

Note, this will reset any existing validators you added when you created the FormControl.

这篇关于Angular如何在创建控件后将验证器添加到FormControl?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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