【发布时间】:2017-02-08 04:15:41
【问题描述】:
好的,让我先描述一下我真正想要解决的问题。
我需要我的表单模型具有这种结构:
{
nested: {
first: 'one',
second: 'two',
third: 'three',
forth: 'four', ...
}, ...
}
子属性将根据用户输入动态添加到模型中,并且嵌套级别的数量可以变化。
实现看起来像这样:
初始化表单:
ngOnInit() {
this.form = this.fb.group({
nested: this.getControls() // of type FormGroup
});
}
加载控件:
getControls(): FormGroup {
let group: FormGroup = new FormGroup({});
Object.keys(this.controls).forEach((key) => {
let control: FormControl = new FormControl(this.controls[key]);
group.addControl(key, control);
})
return group
}
带有 *ngFor 的模板:
<div *ngFor="let control of form.get('nested').controls | keys; let i = index">
<label>{{ getLabel(i) }}</label>
<input [attr.placeholder]="control.value">
</div>
添加新的控制方法:
addControl(key, value) {
let control: FormControl = new FormControl(value)
this.form.get('nested').addControl(key, control);
this.cdf.detectChanges();
}
Plunkr 上提供的精简实现
现在,我遇到的问题是模型的值会更新,但模板没有使用添加的输入重新渲染。
我已尝试强制触发更改检测,但没有成功。
我了解使用 FormArray 提供更多动态功能,但它会产生如下输出:
{
nested: [
{ first: 'one' },
{ second: 'two' },
{ third: 'three' },
{ forth: 'four' }, ...
], ...
}
这让我们回到了问题的根源。
当然,我可以利用一个函数将模型转换回所需的格式,然后再将其推送到数据库中,但考虑到模型在树的不同级别上可能有几个不同的属性,而对于某些我可能会显示为数组,有些可能不会,事情很容易变得过于复杂。
这给我留下了FormGroup,但是我如何确保模板在应用新输入时呈现?谢谢!
【问题讨论】:
标签: angular angular2-template angular2-forms