在 Angular 中动态地将控件添加到 FormGroup [英] addControl to FormGroup dynamically in Angular

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

问题描述

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

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

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

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 中动态地将控件添加到 FormGroup的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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