I have a model which is an array element and it's corresponding HTML view is as below:
<div *ngIf="flag" >
<table id="table" class="table table-hover table-bordered table-mc-light-blue">
<thead>
<tr>
<th>col 1</th>
<th>col 2</th>
<th>col 3</th>
</tr>
</thead>
<tr *ngFor="let item of collection;">
<td>{{item.col1}}</td>
<td>
<input type="text" class="form-control" [(ngModel)]="item.col2" #input="ngModel" name="input-{{i}}">
</td>
</tr>
</table>
</div>
On some conditions, I am inserting new elements using splice.Please find below code
this.collection.splice(LastIndex, 0, ...newArray);
The problem is that after insertion the previous ngModel values are not getting displayed for certain records. I inspected the element and found ng-reflect-model set to previous values, but I couldn't see the values in input controls.
I got it working by modifying my logic as below:
let tempCollection = this.collection.slice();
//empty the list
this.collection = [];
this.changeDetectorRef.detectChanges(); //needed to reflect changes
//insert elements in the list
tempCollection.splice(LastIndex, 0, ...elements);
//push once again to collection
this.collection.push(...tempCollection);
Instead of directly manipulating the collection, I copied it into the temporary variable called tempCollection for manipulation and cleared the collection variable.
Once manipulation is done, I pushed entire tempCollection to collection. I used this.changeDetectorRef.detectChanges() to reflect the changes, once I had cleared collection.