如何在angular2中使用微调器加载图像 [英] How to load image with spinner in angular2
问题描述
我的应用有很多带有描述的图片.当用户导航时,这些文本首先出现并且图像加载有一些延迟.我想在这里添加一个微调器.在加载图像时显示微调器的指令,并显示像
my app got many images with descriptions. When user navigates these text is coming first and image is loading with some delay. I would like to add a spinner here. A directive which shows spinner while loading the image and shows image like
<myimgdir [src]='myimage.png'></myimgdir>
如何添加微调器并跟踪图像是否加载并显示?
How to add spinner and track the image is loaded or not and display it?
推荐答案
在你的控制器中,添加一个函数来处理 'onLoad' 事件,设置状态为 {loading: false}
:
In your controller, add a function to to handle the 'onLoad' event, setting the state to {loading: false}
:
loading: boolean = true
onLoad() {
this.loading = false;
}
在您的模板中,在状态为 loading === true
时渲染加载 gif(或您想要的任何内容),棘手的部分是您应该隐藏 img带有
[hidden]="true/false"
的 code> 元素,而不是阻止它呈现,因此它实际上会加载 src
,然后只需绑定 onLoad
将控制器中的函数添加到实际图像上的 (load)
事件:
In your template, render a loading gif (or whatever you want) while the state has loading === true
, the tricky part is that you should just hide the img
element with [hidden]="true/false"
as opposed to prevent it from rendering so it will actually load the src
, then just bind the onLoad
function in your controller to the (load)
event on the actual image:
<img *ngIf="loading" src="/assets/loading.gif" alt="loading" />
<img [hidden]="loading" (load)="onLoad()" src="{{ source }}" />
此解决方案在功能上与 AngJobs 的相同,但它更具声明性且 IMO 不那么繁琐.
This solution is functionally the same as AngJobs's, but it's more declarative and a little less cumbersome IMO.
PS:使用 [hidden]="boolean"
而不是 *ngIf
有点麻烦,你应该看看 http://angularjs.blogspot.com/2016/04/5-rookie-mistakes-to-avoid-with-angular.html 以了解原因以及如何安全应用它的解决方案.
PS: Using [hidden]="boolean"
instead of *ngIf
is a bit of a gotcha, you should look to http://angularjs.blogspot.com/2016/04/5-rookie-mistakes-to-avoid-with-angular.html to understand why and for a solution on how to apply it safely.
这篇关于如何在angular2中使用微调器加载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!