I am using ngFor to iterate over a simple array to output list items.
At some point, I want to re-create the array contents and update the ngFor content. Pushing data to the array seems to work as intended (i.e. the item is added onto the end of the list in the component template) but when I recreate the array from scratch, it seems the old data isn't removed?
tests = [{output: '1'}, {output: '2'}];
clear(){
this.tests = [{output: '3'},{output: '4'}];
// this.tests.push({output:'b'});
}
Template
<button (click)="clear()">Clear</button>
<ul>
<li *ngFor="let test of tests">{{test.output}}</li>
</ul>
Expected output should be a list of 1,2 and on button click, recreate the list as 3,4. What I get instead is: 3,4,1,2 (the old data persisting at the end and not removed from DOM?) Using a push results correctly in 1,2,b (with b appended at the end).
What am I doing wrong? How can I effectively recreate the contents of the array and ask ngFor to delete the old DOM and reiterate over the contents correctly?
I've tried using triggering event changes manually (e.g. changeDetectorRef and NgZone and even top-level application-ref) but none of them work as desired.