Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ngIf statement is executed multiple times in Ionic 4

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

enter image description here

could anyone explain this behavior of calling isLoggedIn() and isTrue() multiple times by ngIf directive?

like image 759
x7R5fQ Avatar asked Feb 24 '26 03:02

x7R5fQ


2 Answers

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.

like image 91
Alexis Avatar answered Feb 26 '26 15:02

Alexis


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.

like image 42
Pac0 Avatar answered Feb 26 '26 16:02

Pac0