1

I have an img tag is which src populated dynamically.

<img [src]="dynamicUrl" loader >

dynamicUrl is a variable that is populated with an ajax call's result.

dynamicUrl:string ="";

loader is a directive in which I have done

constructor(private el: ElementRef, private renderer: Renderer2) { }

ngAfterViewInit() {
  let loadingBackground = `background:url("${this.loadingImg}") 50% no-repeat`;
  this.renderer.setAttribute(this.el.nativeElement, "style", loadingBackground);

  this.el.nativeElement.onerror = () => {
     // set the error icon as background
     let errorBackground = `background:url("${this.errorImg}") 50% no-repeat`;
     this.renderer.setAttribute(this.el.nativeElement, "style", errorBackground);
  };
}

Now when the directive is called and control comes to ngAfterViewInit it sets the loadingImg gif to the background, and loader shows for milliseconds on the screen. As default value of dynamicUrl is an empty string (so src resolved to ("http://localhost:3000/")) so it also show missing image icon with loader and it gets in the onerror method and sets the errImg as background, so the error image is visible on the screen.

Now the defaultUrl value get it original value populates so actual image is visible.

How can I show solve this, I just want to show only loader image until the actual image get downloaded in the browser.

1 Answer 1

2

You can put loader directive within div element;

<div loader *ngIf="dynamicUrl == null || dynamicUrl == ''"> </div>

<img [src]="dynamicUrl" *ngIf="dynamicUrl !=null && dynamicUrl != ''">
Sign up to request clarification or add additional context in comments.

Comments

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.