ngular中将addControl动态添加到FormGroup

ngular中将addControl动态添加到FormGroup

本文介绍了在Angular中将addControl动态添加到FormGroup的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Angular中动态地将FormControl添加到FormGroup?

How can I add a FormControl to a FormGroup dynamically in Angular?

例如,我想添加一个强制控件,该控件的名称为"new".其默认值为.

For example,I would like to add a mandatory control which name is "new" and its default value is ''.

推荐答案

addControl 是您所需要的.请注意,第二个参数必须是这样的FormControl实例:

addControl is what you need. Please note the second parameters must be a FormControl instance like so:

this.testForm.addControl('new', new FormControl('', Validators.required));

如果需要,还可以使用 setValidators 动态添加验证器.方法.调用此选项会覆盖所有现有的同步验证器.

You can also add the validators dynamically if you want with the setValidators method. Calling this overwrites any existing sync validators.

这篇关于在Angular中将addControl动态添加到FormGroup的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 02:50