Angular2 ngFor: when add/remove DOM? how to force it recreate DOM?

2k views Asked by At

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'
        });


   }
1

There are 1 answers

5
Günter Zöchbauer On

You can temporarily set objArr to null and "force" Angular to update the DOM by calling detectChanges in between:

constructor(private cdRef:ChangeDetectorRef) {}

onClick() {
  var tmp = this.objArr;
  this.objArr = null;
  this.cdRef.detectChanges();
  this.objArr = tmp;
  this.cdRef.detectChanges();
}