Angular 6-更新数组内部的深层对象

时间:2020-07-05 17:25:05

标签: angular typescript

我有一个配置对象,可以从X组件发送到Y组件

从Y组件中,我过滤列以仅获得唯一的monoselect,然后针对每一列我要更新monoselectConfig的选项。

问题是我可以更新选项,但是当我显示配置对象时,我找不到我刚刚进行的修改

stackblitz

  config = {
    value: this.result,
    columns: [
      {
        field: "speciality",
        type: "monoselect",
        monoselectConfig: { options: this.options },
        unique: true
      }
    ]
  }

1 个答案:

答案 0 :(得分:1)

您正确进行了过滤,但是没有正确更新对象。

我已经在stackblitz中检查了您的代码,您只需要在ngOnChanges()方法中进行少量更改。

因此,只需通过以下代码更新ngOnChanges()方法即可。这也会更新您的配置对象。

ngOnChanges(changes: SimpleChanges) {
    if (changes["config"] && changes["config"].currentValue) {

      this.configuration = changes["config"].currentValue;

      // get all unique monoselect
      let monoselectsUnique = this.configuration.columns.filter(element => element.type === "monoselect" && element.unique == true);
      console.log(monoselectsUnique)
      if (monoselectsUnique.length > 0) {
        monoselectsUnique.forEach(element => {

          // get all options not exist in the array result
          let newOption = element.monoselectConfig.options.filter(item => !this.config.value.map(item => item[element.field].code).includes(item.code));

          // update the config object with the new option
          // monoselectsUnique = { ...monoselectsUnique.monoselectConfig, options: newOption }
          element.monoselectConfig.options= newOption
        })
         console.log(monoselectsUnique)
        console.log(this.configuration)
      }

    }
  }
相关问题