Search code examples
javascriptangularangular5angular-ng-if

Angular5 *ngIf=“afunctioncall(); let L” results in the function being called 4 times


I am working with Angular 5 and I want an element to return an object after finding from an array upon the result of a function call and then I use let L as a variable object to hold that.

When I do this I've noticed that the function is called multiple times.

enter image description here

I have created a stack-blitz to show this situation. here that function is called 4 times but in my local application, it is called more than 6 times.

https://stackblitz.com/edit/angular-ypwswn

I know this is because of change detection cycle. but I could not figure out how to solve this situation logically.

I've seen the following post however with it being related to Angular 2. I'm not sure it's relevant

Angular2 *ngIf="afunctioncall()" results in the function being called 9 times

The 'console.log is output 4 times.

Can anyone point me or am I missing anything?

And is there any way to avoid it?

Any help will be appreciated.

I need to pass a array to that method and get a selected leg from that array.

This is View This is method


Solution

  • call the function in ngOnInit instead on your template

    export class AppComponent implements OnInit {
    
    finaldata : any;
    
    
    ngOnInit() {
    
         this.finaldata = this.getSelectedLeg(this.data);
    
      }
    
    
    }
    

    in html

    <div *ngIf="finaldata; let L">
    
    </div>