动态更改Angular中的src属性时如何隐藏图像

时间:2019-03-04 17:47:04

标签: javascript angular angular6

在更改src标签值时,是否可以在加载新图像时隐藏或删除图像。

示例代码:

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

在组件中:

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

此代码的问题在于,单击按钮后,旧图像仍显示,直到新图像完全加载为止,这是不希望的。
是否可以删除它或显示正在加载新图像的提示?

请注意:我的情况不允许一次预加载很多图像的解决方案。

3 个答案:

答案 0 :(得分:1)

您可以如下使用*ngIf从DOM中删除图像,

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

您可以将变量设置为空字符串' ',如下所示

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

答案 1 :(得分:1)

只需连接图像的加载事件即可。

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;
  }

答案 2 :(得分:0)

您可以在img标签中使用* ngIf。

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

然后您可以在组件中做出决定。

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