【问题标题】:Angular Input property change is not detected when I push new item in array当我在数组中推送新项目时,未检测到角度输入属性更改
【发布时间】:2021-12-24 02:14:09
【问题描述】:

我有一个数组(数据源)列表,我正在对它执行添加和删除操作。我在子组件中传递了一个数组(数据源)并在子组件中添加了 *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

【问题讨论】:

    标签: javascript angular typescript angular-material angular-reactive-forms


    【解决方案1】:

    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',
      }
    ];
    

    【讨论】:

    • 感谢@majusebetter 的解释。它按预期工作。但在真实场景中,我的dataSource是FormArray。那么,我该如何为其分配一个新值呢?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-18
    相关资源
    最近更新 更多