Riddhi
Riddhi

Reputation: 202

Angular2 table is not refreshing data

I have an Angular2 application which is getting Json data and displaying it as a table. When I try to refresh / Update it with new data, table is showing old data only.

getting data through service like below:

@Input()
participants:Participant[]; 

testClasses: TestClass[] = []; 

ngOnChanges() {  
   let codes="";

   for (let item of this.participants)
   {
      codes = codes.concat(item.Id).concat(",");
   }   
   this.buildTable(codes);
}

buildTable(codes){

    let url = this.serverUrl + "api/test?codes=" + codes;

    // passing input participants as parameter in url
    this.testService.getData(url)
      .subscribe(data => this.onDataUpdate(data));
}

onDataUpdate(data: any) {
    this.testClasses = data;     
    // here I am getting new/refreshed data.
}

displying in table like below:

<table id="testGrid">
  <tr *ngFor="let testClass of testClasses">
    <td>{{testClass.name}}</td>
    <td *ngFor="let t of (testClass.Score)">
       {{ t }}
    </td>
  </tr>
</table>

When page loads data first time, table is showing data, but when I try to refresh data, I can see new refreshed data in onDataUpdate funcion, but html table is not refreshing view with new data.

Any idea or help would be much appreciated.

I tried below link:

https://github.com/swimlane/ngx-datatable/issues/255

Angular 2 - View not updating after model changes

Upvotes: 0

Views: 3468

Answers (1)

runit
runit

Reputation: 376

I made my own example and I was able to reproduce the behaviour. So what going on here it's that you use an array as input. (participants:Participant). And after what you said about your checkboxes its seems that you mutate your array. It has for effect that the reference of the array is still the same therefor angular don't detect a change. (by the way I don't know if it's an expected behaviour).

A solution to your problem could be to create a new array of participants at each change on checkboxes.

Something like that: this.participants = this.participants.slice(0)

You could also look at this answer: Angular2 change detection: ngOnChanges not firing for nested object

Upvotes: 2

Related Questions