繁体   English   中英

当表单模型中的值更新时,如何强制 Angular 2 更改检测?

[英]How to force Angular 2 change detection when value in the form model updates?

好的,让我开始描述我真正想要解决的问题。

我需要我的表单模型具有以下结构:

{
  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但是我如何确保模板在应用新输入时呈现? 谢谢!

我可以为您提供以下解决方案:

1) 使用不纯的管道

@Pipe({
  name: 'keys',
  pure: false
})

Plunker 示例

2) 添加控件后传递新的引用

addControl(key, value) {
  this.controls[key] = value;
  this.form = this.fb.group({
    nested: this.getControls()
  });
}

Plunker 示例


我还删除了getLabel函数并将映射控件名称添加到您的管道

keyArr.forEach((key) => {
   value[key].name = key;
   dataArr.push(value[key])
})

也可以看看

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM