简体   繁体   中英

Angular: ngFor not updating the view when the objects of array are changed

I am trying to show some tabs based on an ngFor loop in the view. I am constantly changing the array of objects to show or hide tabs. But some tabs are staying active, because I think the objects inside the array are not updating.

The array is called from the service and is updated on the service from different components.

Here is the code:

html:

<kendo-tabstrip-tab *ngFor="let report of this.reportService.reportsSelectedService" [selected]="report.selected" >
          <ng-template kendoTabTitle >
            <span (click)='clickDetailReport()'>{{report.name}}</span>
            <i (click)="onCloseReportDetail(report.name)" class="fa fa-times close-tab" aria-hidden="true"></i>
          </ng-template>
          <ng-template kendoTabContent *loadOnDemand>
            <app-report-details [reportData]="report"></app-report-details>
          </ng-template>
        </kendo-tabstrip-tab>

component.ts

redirect(name:string, url:string){
    this.reportService.isReportsTabSelected = false;
    let obj = {
      name: name,
      url: url,
      selected: true
    }
    
    this.reportService.reportsSelectedService.forEach((item) => {
        item.selected = false;
    });
    this.reportService.reportsSelectedService.push(obj);
  }

I have tried ChangeDetectorRef and trackBy: custom method


This error is related to the way ChangeDetectorRef works, you can see further information here .

You're mutating the array but you're not updating the reference to that array. That means that for Angular the array didn't change. To avoid this you need to create a new array and assign that to the variable. You can use the map method to achieve this:

redirect(name:string, url:string){
this.reportService.isReportsTabSelected = false;
let obj = {
  name: name,
  url: url,
  selected: true
}

const newArray = this.reportService.reportsSelectedService.map((item) => {
    item.selected = false;
    return item;
});
newArray.push(obj);
this.reportService.reportsSelectedService = newArray;

}

Only ChangeDetectorRef can solve this.

Working demo at StackBlitz .

Demo Result:

在此处输入图像描述

this.titles = [...this.titles];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM