Angular 输入 属性 当我在数组中推送新项目时未检测到更改

Angular Input property change is not detected when I push new item in array

我有一个数组 (dataSource) 列表,我正在对它执行添加和删除操作。我在子组件中传递了一个 array(dataSource) 并在子组件中添加了 *ngFor 循环。我已作为 getter setter 传递的数组用于检测 @Input 更改。

这是我的 AppComponent :

<div>
    <vertital-tabs
          [config]="config"
          [dataSource]="dataSource"    <-- Array changes I want to detect in Child
          [(selectedItem)]="selectedItem">
    </vertital-tabs>

    <div style="background-color: yellow;margin: 10px">
        {{ selectedItem | json }}
     </div>
</div>

ChildComponent(垂直制表符)中:

get dataSource(): any {
    return this._dataSource;
}

@Input() set dataSource(value: any) {
    this._dataSource = value;
    // Not called this on Add New button even if Input Datasource is changed.
    // I want this to be called on Add New Item button click....
    debugger;
}

问题 是当我在数组上添加新项目时,它没有调用 setter @Input 更改方法。当我删除一个项目时它工作正常并调用@Input change.

注意:我在实际场景中有很多属性作为输入,所以我不想使用 ngOnChanges()

这是我创建的示例:https://stackblitz.com/edit/angular-vertical-tabs-component-split-yzynef

Angular 仅检查 reference 是否已更改 - 如果自上次检查以来未更改,则不会调用 setter。

app.component.ts中:

let nextItem = this.dataSource.length;
this.dataSource.push({
  id: nextItem.toString(),
  text: 'item ' + nextItem.toString(),
  icon: 'settings',
});

在这里,您向数组中添加一些内容,而不是创建一个新数组并将其分配给 dataSource

vertical-tabs.ts中:

onDelete(item, index) {
  this.dataSource = this.dataSource.filter((x) => x !== item);
}

这里创建一个新数组并将其赋值给dataSource

这就是为什么删除会如您所愿,但添加却不会。复制数组并将其分配给 dataSource 应该可以解决您的问题:

let nextItem = this.dataSource.length;
this.dataSource = [
  ...dataSource,
  {
    id: nextItem.toString(),
    text: 'item ' + nextItem.toString(),
    icon: 'settings',
  }
];