1

Template is:

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

Component is:

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

I see that variable was chnaged on a new value: row = postaddress; but template does not render.

I use changeDetection: ChangeDetectionStrategy.OnPush

Also I have tried this:

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

2 Answers2

1

It has nothing to do with changeDetection, when assigning row = postaddress; the reference to the original row is lost, thus is not pointing to the one in the array any more, (row doesn't contain the row itself, rather a reference to it, when assigning to it a new object, it would hold a reference to the new object.)

public edit(row: PostAddress): void {
  dialogRef.afterClosed().subscribe((postaddress) => {
    if (postaddress)
    {
      rows.splice(rows.indexOf(row), 1, postaddress)
    }
  }

Or optionally using index provided by ngFor:

public edit(row: PostAddress, index : number): void {
  dialogRef.afterClosed().subscribe((postaddress) => {
   if (postaddress)
   {
    rows[index] = postaddress
   }
}
Rafi Henig
  • 5,950
  • 2
  • 16
  • 36
1

Instead of reassigning a element in the array, you could try to send the index and modify the element in the parent array. Try the following

Template

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

Controller

public edit(index): void {
  dialogRef.afterClosed().subscribe((postaddress) => {
    if (postaddress) {
      this.rows[i] = postaddress;     // <-- change item in the array
      this._change.markForCheck();
    }
  }); 
}
ruth
  • 29,535
  • 4
  • 30
  • 57
  • could you explain why link is lost? –  Aug 21 '20 at 12:46
  • Object assignments are finicky in Javascript. They are pseudo pass-by-reference. So when you assign another object to the variable, it ceases the reference. You could refer [here](https://stackoverflow.com/a/3638034/6513921) and [here](https://stackoverflow.com/a/37290849/6513921) for more info. – ruth Aug 21 '20 at 13:00