【问题标题】:How to force Angular 2 change detection when value in the form model updates?表单模型中的值更新时如何强制Angular 2更改检测?
【发布时间】: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


    【解决方案1】:

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

    1) 使用impure pipe

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

    Plunker Example

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

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

    Plunker Example


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

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

    另见

    【讨论】:

    • 好的!我从不怀疑管道,肯定会进一步调查纯管道与不纯管道。完美的答案。
    猜你喜欢
    • 2017-06-30
    • 1970-01-01
    • 1970-01-01
    • 2012-05-06
    • 2019-09-18
    • 1970-01-01
    • 2016-06-02
    • 2017-05-09
    • 1970-01-01
    相关资源
    最近更新 更多