I have a component where I'm showing some charts and a table beside it that shows that latest value of each chart.
I'm doing this for each object in an array, like this:
<div class="patient-box level-2" *ngFor="let bed of patientService.bedsLevel2" draggable="true" (dragstart)="onDrag($event, bed)">
...
<table class="vsTable">
<tr>
<th [matTooltip]="translations?.Tooltip.Type">Type</th>
<th [matTooltip]="translations?.Tooltip.AverageReading1624">16-24t</th>
<th [matTooltip]="translations?.Tooltip.Chart" translate>Chart</th>
<th [matTooltip]="translations?.Tooltip.AverageReading01">0-1t</th>
</tr>
<tr *ngFor="let vitalSign of vitalSigns; let i = index">
<td [matTooltip]="getTooltip(vitalSign)">{{vitalSign}}</td>
<td>{{getVitalSign(bed.timeWindows[5], vitalSign)}}</td>
<td>
<chart [options]="lineChartOptions" (load)="saveLineChart($event.context, vitalSign, bed)" draggable="true"></chart>
</td>
<td>{{getVitalSign(bed.timeWindows[0], vitalSign)}}</td>
</tr>
</table>
Every now and then, I'm making a call to a server to update the patientService.bedsLevel2 array:
updateBeds() {
this.patientService.bedsLevel2.forEach(bed => {
this.patientService.getBedDetails(bed.cetreaName).subscribe(
(result: BedDetails) => {
this.updateChartData(result);
bed = result;
},
err => {
console.log(err);
}
);
});
this.updateBedsTimeout = setTimeout(() => this.updateBeds(), BED_UPDATE_INTERVAL);
}
As you can see in the code, I am using the result to update the chart data, and then I'm assigning it as a new value to the bed object. When this method completes, the view of the chart has been updated, but the data in the table next to it has not.
I've read that Angular doesn't detect changes unless the reference to the array changes, so I've tried adding each of the following to the end of the updateBeds() method:
this.patientService.bedsLevel2 = [...this.patientService.bedsLevel2];
this.patientService.bedsLevel2 = this.patientService.bedsLevel2.slice();
None of them fixed the problem though. What could be causing this problem, why doesn't my attempt to fix it work, and what will fix it? I've read something about manually making change detections with ChangeDetectorRef, so I might try that out.
bed = resultis just changing the pointer for thebedlocal variable to point at your new result. That isn't changing the reference in your array.forEachof of the array wherebedrepresents each object.bedis a variable that points to your object in memory. When you re-assign a value to that variable, you are simply changing what that local variable is pointing to... this has no impact on the value in the array.