防止在* ngFor内加载一些图像

时间:2017-03-08 09:13:01

标签: angular

我在* ngFor中有一个图像列表,我需要控制图像的加载:

  1. 首次加载索引号为X
  2. 的图像
  3. 当所有其他图像都被加载时,触发一个功能
  4. 我的目标是首先尽快显示最重要的图像,而不会有其他图像占用带宽。

    我找到了一些javascript解决方案,但他们都使用了角度团队不允许或推荐的文档和窗口对象。

    我有一个非常简单的模型和视图。它甚至可能吗?

    var images = ['src1','src2','src3','src4'];
    
    <div *ngFor = "let img of images"> {{img}} </div>
    

2 个答案:

答案 0 :(得分:2)

images = ['src1','src2','src3','src4'];
isImportantLoaded = false;
// set values to true for indexes that matches important images
// after all were set to false, set isImportantLoaded to true, 
// to get the non-important images loaded
importantImages = [false, true, false, true];

setLoaded(idx) {
  this.importantImages[idx] = false;
  var found = this.importantImages(true);
  if(found < 0) {
    this.isImportantLoaded = true;
  }
}

<ng-container *ngFor="let image of images, let i=index">
  <img (load)="setLoaded(i)" [href]="image" *ngIf="isImportant[i] || isImportantLoaded">
</ng-container>

答案 1 :(得分:0)

试试这个:

<div *ngFor = "let img of images">
   <img [src]="img" (load)="onLoad($event)"/>
 </div>
组件中的

onLoad($event){
    //do something $event.target
}