首页 > 解决方案 > ngFor 会自动更新

问题描述

我有一个列表,list-components如下所示:

list.components.ts

import { BsModalService, BsModalRef } from 'ngx-bootstrap/modal';
import { EditModalComponent } from "...../edit-modal.component";

@Component({
   selector: 'list',
   templateUrl: './list.component.html',
   providers: [ Service ]
})
export class ListComponent implements OnInit {
    bsModalRef: BsModalRef;
    list:[];

    constructor(private modalService: BsModalService, private service: Service) {  }

    ngOnInit() { this.service.getList().subscribe(data => this.list = [...data ] )  }

    edit({ thisData }) {
       const initialState = { data: thisData };
       this.bsModalRef = this.modalService.show(EditModalComponent, { initialState });
       this.bsModalRef.content.updateSingleValue = (id, name, value) => this.service.update(id, { [name]: value })
    }
}

list.components.html

<table-list [(data)]="list" (action)="edit($event)"></table-list>

现在调用table-list组件,如下所示:

表列表.components.ts

@Component({
  selector: "table-list",
  inputs: ["data"],
  templateUrl: "./table-list.components.html"
})
export class TableListComponent implements OnInit, OnChanges {
    @Input() data: any[];
    @Output() editAction = new EventEmitter();

    handleEdit($root) {
       this.editAction.emit({ thisData: $root });
    }

    ngOnChanges(changes: SimpleChanges) {
       // this will execute in every form data update
    }
}

表-list.components.html

<table>
   <tr *ngFor="let $root of data">
      <td> {{ $root.name }} </td>
      <td> {{ $root.email}} </td>
      <td> <button (click)="handleEdit()">edit</button> </td>
  </tr>
</table>

如您所见,这里只显示数据列表和一个编辑按钮。当用户点击编辑按钮时,它会edit({ thisData })调用list.component.ts. 然后edit({ thisData })方法将打开一个modalwith input form。因此,当用户编辑任何表单数据时,它将执行以下代码并更新单个数据。它工作正常。

this.bsModalRef.content.updateSingleValue = (id, name, value) => this.service.update(id, { [name]: value })

我的问题是,当用户更新任何表单数据时,它也会全部更新list-data(重新生成列表)。我只想更新列表中的单个数据(不想重新生成列表)。我放了一些调试器,发现当任何表单数据更新时,它会触发table -list.component.ts并重新生成listngOnChanges(changes: SimpleChanges)

我怎么解决这个问题?提前致谢。

标签: angular

解决方案


trackBy在你的*ngFor循环中使用。这样,只有已更改的项目才会重新呈现。在此处查看最佳答案


推荐阅读