问题描述
我们有一个具有动态生成表单的组件.添加带有验证器的控件的代码可能如下所示:
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);
但是,假设我要添加第二个验证器稍后.我们怎样才能做到这一点?我们无法在此在线找到任何文档.我确实发现,虽然在表单控件中有setValidators
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.
推荐答案
您只需向FormControl传递一个验证器数组.
You simply pass the FormControl an array of validators.
下面是一个示例,显示如何将验证器添加到现有FormControl:
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)]);
注意,这将重置在创建FormControl时添加的所有现有验证器.
Note, this will reset any existing validators you added when you created the FormControl.
这篇关于在Angular中,如何在创建控件后将Validator添加到FormControl?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!