blgrnboy blgrnboy - 1 month ago 9
Javascript Question

Angular2: ngFor keeps executing after page is rendered

I am creating a re-usable table component. While trying to implement pagination on that component, I first noticed that I wasn't able to do a simple "for" loop without creating a dummy array.

As kind of hack, I implemented the following:

HTML:

<ul class="pagination hidden-xs pull-right">
<li *ngFor="let item of createRange(); let pageNum = index;">
<a (click)="goToPage(pageNum+1)">{{pageNum+1}}</a>
</li>
</ul>


Component:

createRange() {
var items: number[] = [];
for (let i = 1; i <= this.totalPages; i++) {
items.push(i);
}
console.log(items);
return items;
}


The problem here (or maybe expected behavior) is that I see on seeing that dummy object logged to the console, over and over again, even when it looks like that page is done rendering.

Is this because it wants to keep checking for changes? Is there a more efficient way for me to display the number of pages in the HTML so that it doesn't keep calling the
createRange()
method over and over again?

Answer

For binding, you should not use function rather use variable. If you use function, it will be called every time when angular2 runs binding check. use of function for binding is not recommended at all.

<li *ngFor="let item of myArr; let pageNum = index;">    //<<<@@@ myArr
        <a (click)="goToPage(pageNum+1)">{{pageNum+1}}</a>
    </li>

constructor(){
   this.myArr=this.createRange();                        //<<<@@@ using myArr variable.
}

createRange() {
    var items: number[] = [];
    for (let i = 1; i <= this.totalPages; i++) {
        items.push(i);
    }
    console.log(items);
    return items;
}
Comments