Search code examples
angularangular6angular-ng-if

How to prevent the delay in evaluating ngIf condition in angular 6? Default image is displayed before evaluating the value. How to prevent this?


component.ts

  this.canShowPrivateInfo;

  if (this.canEditDetails || this.loginId == this.loggedInUser) {                    
      this.canShowPrivateInfo = true;
  } else if (this.loggedInUserPrivacy) {
      this.canShowPrivateInfo = false;
  } else {
      this.canShowPrivateInfo =true;
   }

This is the condition ( this.canShowPrivateInfo ) which is used to toggle between showing protected image and normal image

HTML

PUBLIC IMAGE

<img *ngIf="canShowPrivateInfo" 
     [src]="uploadedImageURL" 
      class="profile-pic"
 >

PROTECTED IMAGE

<span *ngIf="!canShowPrivateInfo" class="profile-pic">
  <i class="fas fa-user-lock profile-lock"></i>
</span>  

So here even if canShowPrivateInfo is true, it is first showing lock image and then it is showing actual image.

It is taking a second to evaluate and then changing.

How can I prevent this flickering of images initially in screen? Which is the best way to toggle between images without flickering?


Solution

  • To avoid this flickering you can do:

    • Do not assign false to canShowPrivateInfo as the time of declaring the variable.
    • Then in HTML add undefined check as well.

    eg:

    TS:

    public canShowPrivateInfo;
    

    HTML:

    <span *ngIf="!canShowPrivateInfo && canShowPrivateInfo !== undefined"
          class="profile-pic">
           <i class="fas fa-user-lock profile-lock"></i>
    </span>