-4

I have a simple array, with 6 objects in it. http://prntscr.com/jwp54d

I do a simple *ngFor="" that should and does show me 6 lines.

<ng-container *ngFor="let rec of deal.recycles">
    <div *ngIf="checkReasonFilter(rec)" class="row" routerLink="/company" [queryParams]="{id: deal.withCompany}" fragment="recycled" >

I have added a counter to my checkReasonFilter(rec) function, and on load it is called 672 times!

How, why? Anyone has any clue?

The function is called only once, here!

Thanks!

Magor Menessy
  • 381
  • 4
  • 13
  • 2
    `*ngIf` is called in every change detection circle not only once when rendering, so your function is called 6 times in every turn of change detection so it sum's up – Fussel Jun 19 '18 at 11:51
  • 1
    Usage of functions in bindings is discouraged ,Your function will be called on every change detection cycle and angular runs x2 cycles in dev mode. – Vikas Jun 19 '18 at 12:27

2 Answers2

2

Magor, When you get the deal.recycles you can map the array

deal.recycles=dealrecycles.map(rec=>{

        return {
           ...rec,  //<---all the properties of rec
           show:checkReasonFilter(rec)   //<--anohter one
        }
    })

So, you has a new property "show", that you can use in the *ngFor

Eliseo
  • 50,109
  • 4
  • 29
  • 67
0

because every time angular run it's digest cycle function gets called. it's not a common practice to add a function inside ngIf condition if the function has complex logic.

Best way to approach this is to add a variable inside ngIf and whatever you do in that function assign the end result to the newly created variable

Sachila Ranawaka
  • 39,756
  • 7
  • 56
  • 80