在Angular中,创建控件后如何将Validator添加到FormControl? [英] In Angular, how to add Validator to FormControl after control is created?
问题描述
我们有一个具有动态构建表单的组件.添加带有验证器的控件的代码可能如下所示:
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 12 更新
从 Angular 12 开始,如果您想在不删除现有验证器的情况下向表单添加新的验证器,可以使用 addValidator
:
Since Angular 12, if you want to add new validators to the form without removing the existing validators, you can use addValidator
:
this.form.controls["firstName"].addValidators([Validators.minLength(1), Validators.maxLength(30)]);
这篇关于在Angular中,创建控件后如何将Validator添加到FormControl?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!