Detect changes in objects inside array in Angular2

后端 未结 2 700
轻奢々
轻奢々 2020-11-30 04:29

Using Angular 2 and typescript. I have an array that I use DoCheck and IterableDiffer to listen to changes in my code. When the array is changed I get notifications, but whe

2条回答
  •  离开以前
    2020-11-30 04:59

    I found inspiration in Thierry Templiers answer but it did not work for me- I modified it and ended up with this solution:

    You have this private variable:

     private objDiffers: Array>;
    

    You want to watch each element in an Array. In this case the array type is Array. The constructor should look like this:

      constructor(
        private differs: KeyValueDiffers) {
        this.itemGroups = new Array();
        this.differ = this.differs.find(this.itemGroups).create();
      }
    

    ngOninit like this:

      public ngOnInit(): void {
        this.objDiffers = new Array>();
        this.itemGroups.forEach((itemGroup, index) => {
          this.objDiffers[index] = this.differs.find(itemGroup).create();
        });
      }
    

    and ngDoCheck like this:

    ngDoCheck(): void {
        this.itemGroups.forEach((itemGroup, index) => {
          const objDiffer = this.objDiffers[index];
          const objChanges = objDiffer.diff(itemGroup);
          if (objChanges) {
            objChanges.forEachChangedItem((changedItem) => {
              console.log(changedItem.key);
            });
          }
        });
      }
    

    Now you will notice that each time an item within the array changes you will get a console log with that item and with the property that has changed.

提交回复
热议问题