I am playing with Angular2 *ngFor and have a little confusing about when it recreate DOM.
If I only have case 1 code inside onClick()
, then it will recreate two <li>
, but I just assign the same value to this.objArr.
If I only have case 2 code inside onClick()
, then it doesn't recreate two <li>
, and just add one more <li>
. I wonder how ngFor determine when to recreate DOM.
What I want to do is:
If I just push more object into the existing array, how can I let it recreate the existing DOM for me besides add DOM for the pushed object? Like in case 2, I hope ngFor can recreate the first two <li>
for me.
Html:
<button (click)="onClick($event)"></button>
<li *ngFor="let obj of objArr"></div>
.ts file:
constructor() {
this.objArr = [
{
'id': 0,
'content': 'test0'
},
{
'id': 1,
'content': 'test1'
}
];
}
onClick() {
// case 1: recreate two <li>
this.objArr = [
{
'id': 0,
'content': 'test0'
},
{
'id': 1,
'content': 'test1'
}
];
// case 2: just add one <li> after the two existing <li>
this.objArr.push({
'id': '2',
'content': 'test2'
});
}
You can temporarily set
objArr
to null and "force" Angular to update the DOM by callingdetectChanges
in between: