0

Is there a way to hide or remove image while loading a new one, when changing src tag value.

Example code:

<img [src]="dynamicPath">
<button (click)="changeSrc()">Change Image Src</button>

In component:

dynamicPath = 'somePath.jpg';
changeSrc(){
    this.dynamicPath = 'newPath.jpg';
}

The problem with this code is that after clicking the button, old image is still showing until new image has completely loaded, which is undesired.
Is there a way to remove it or show a hint that new image is being loaded?

Note that: my case doesn't allow solution of preloading many images at once.

2
  • 2
    Use ngClass on the image element. Within your changeSrc() method change the property that would add a class that might include a "spinner" opaquely over the existing image. Use an onload handler for the image to remove the spinner class dynamically via ngClass Commented Mar 4, 2019 at 17:52
  • @RandyCasburn, thank you... So obvious yet It didn't cross my mind... I'm using onload event to hide spinner after initial loading, but somehow I forgot that I can reset that property when pressing the button. Commented Mar 4, 2019 at 18:09

3 Answers 3

2

Just hookup the load event of the image.

html

<img [src]="dynamicPath" (load)="onload()" *ngIf="loadingImg">
<button (click)="changeSrc()">Change Image Src</button>

ts

loadingImg = true;
dynamicPath = 'somePath.jpg';
changeSrc(){
    this.loadingImg = true;
    this.dynamicPath = 'newPath.jpg';
}

  onload() {
    this.loadingImg = false;
  }
Sign up to request clarification or add additional context in comments.

1 Comment

This is a great solution because it also allows you to add a fade out and in effect via CSS by adding a class as soon as the image is changed and removing this class again when the image is loaded.
1

You can remove the image from the DOM using *ngIf as below,

<img *ngIf="dynamicPath!=''" [src]="dynamicPath">
<button (click)="changeSrc()">Change Image Src</button>

you can set the variable to empty string ' ' as below

dynamicPath = 'somePath.jpg';
changeSrc(){
      this.dynamicPath ='';
      this.dynamicPath = 'newPath.jpg';
}

Comments

0

you can use *ngIf in the img tag.

<img *ngIf="!loading" [src]="Path">
<button (click)="changeSrc()">Change Image Src</button>

Then you can make decision in the component.

Path = 'somePath.jpg';
loading=false;
changeSrc(){
  this.loading =true;
  this.Path = 'newPath.jpg';
  this.loading =false;
}

1 Comment

As far as I know, this won't solve the issue with the time the browser has to actually load the image.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.