首页 > 解决方案 > 为什么模板没有改变?- 角

问题描述

模板是:

  <tr *ngFor="let row of rows; let i = index">
     <div (click)=""edit(row)></div>
  </tr>

组件是:

 public edit(row: PostAddress): void {
      dialogRef.afterClosed().subscribe((postaddress) => {
            if (postaddress) {
                row = postaddress;
                 this._change.markForCheck();
            } 
 }

我看到该变量已更改为新值: row = postaddress;但模板未呈现。

我用 changeDetection: ChangeDetectionStrategy.OnPush

我也试过这个:

 row = postaddress;
 this._change.markForCheck();
 this._change.detectChanges();

标签: angular

解决方案


您可以尝试发送索引并修改父数组中的元素,而不是重新分配数组中的元素。尝试以下

模板

<tr *ngFor="let row of rows; let i = index">
  <div (click)="edit(index)></div>
</tr>

控制器

public edit(index): void {
  dialogRef.afterClosed().subscribe((postaddress) => {
    if (postaddress) {
      this.rows[i] = postaddress;     // <-- change item in the array
      this._change.markForCheck();
    }
  }); 
}

推荐阅读