typescript 如何将 FormControl 动态添加到 FormGroup

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43717248/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:30:01  来源:igfitidea点击:

How to add dynamically FormControl to FormGroup

angulartypescript

提问by István

I have this plunker. I am creating form components dynamically, based on model(defined in app.ts), and cannot add

我有这个plunker。我正在动态创建表单组件,基于model(在 中定义app.ts),并且无法添加

formControlName = "name"

formControlName = "name"

to the component. In the control-factory.directive.tsI add

到组件。在control-factory.directive.ts我添加

this.form.addControl(this.model.name, new FormControl());,

this.form.addControl(this.model.name, new FormControl());,

but how can I bind the value?

但是我怎么能绑定这个值呢?

回答by yurzui

To keep form value in sync with your custom model i would subscribe to control.valueChanges

为了使表单值与您的自定义模型同步,我会订阅 control.valueChanges

let control = new FormControl(this.model.data);
control.valueChanges.subscribe(x => {
  this.model.data = x;
});
this.form.addControl(this.model.name, control);

to keep in sync form model and view i would bind FormControlto reactive directive i.e. formControl

为了保持同步表单模型和视图,我将绑定FormControl到反应指令,即formControl

datepicker.component.html

日期选择器.component.html

<input [formControl]="form.get(model.name)">

Modified Plunker

改良的Plunker