I am using ionic 4 and I have a problem using ngIf directive. The problem is that the ngIf directive statement is executed multiple times. Pay attention to *ngIf="isLoggedIn()".
I have this in tab3.page.html
<ion-header>
<ion-toolbar>
<ion-title>
Tab Three
</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<ion-card>
<div *ngIf="isLoggedIn()">
<div class="ion-padding">
<ion-button expand="block" type="submit" class="ion-no-margin" routerLink="/tabs/tab3/register">Sign up</ion-button>
<br>
<ion-button expand="block" type="submit" class="ion-no-margin" routerLink="/tabs/tab3/login">Log in</ion-button>
</div>
</div>
<!-- <div *ngIf="isLoggedIn()">
You are logged in
</div> -->
<p *ngIf="isTrue()">
Paragraph. True.
</p>
</ion-card>
</ion-content>
and I have this in tab3.page.ts
isLoggedIn(): boolean {
console.log('isLoggedIn called');
let logged: boolean = false;
return logged;
// this.authService.loggedIn()
// .then( val => {
// logged = val;
// });
// return logged;
}
isTrue() {
console.log('isTrue() called');
return true;
}
In the browser console, this is the output

could anyone explain this behavior of calling isLoggedIn() and isTrue() multiple times by ngIf directive?
Structural directives are responsible for HTML layout. They shape or reshape the DOM's structure, typically by adding, removing, or manipulating elements.
Structural directives
*ngIf is checking every time if the data you passed in it is true or false. So in your case it's calling isLoggedIn() or isTrue() several times to check is the result has changed.
As explained by Alexis' answer, the function is evaluated regularly (I call this "polling") to check if status has changed.
If you think this has a performance hit, you could use a property instead, and update it accordingly when it's needed. This lead to potentially much more code all around your component where the value needs to be updated, though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With