简体   繁体   中英

How to force recreate <img /> when src changes?

I have an Angular component like this:

import { Component, Input } from '@angular/core';

@Component({
  selector: 'picture',
  templateUrl: './picture.html',
})
export class Picture {
  @Input() pictureUrl: string;
}
<img src="{{pictureUrl}}" />

The problem is that when the pictureUrl input attribute changes, Angular just changes the src attribute of <img /> so the browser shows the previous picture until the new one is loaded. The desired behavior is to show nothing or draw the new picture progressively as it's being load instead of showing the stale picture. Usually it's solved by recreating the <img /> DOM element when the picture URL is changed.

So the question is: how to force Angular 8 recreate/remount the <img /> element when its src attribute is changed? Or how is the described problem solved in Angular?

To clarify the question: if I were using React, I'd solve it by adding the key={pictureUrl} prop to <img /> .

You can bind a load event to the image as

<img (load)="HideLoader()" />

The load event will fire once the image is loaded. You may use an overlay to show a loading icon once you change the image src and hide the loader once the image is loaded ie when the load event is fired.

You can detect change in the input propery by writing your own setter as

@Input() set thePictureURL(url: string) {
    //show loader
    this.pictureUrl = url;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM