如何在* ngIf HTML中获取.ts var值?

问题描述 投票:0回答:1

我试图全部显示2秒钟的图像,我设法先全部显示它们。

这是我的HTML行:

<img id="bh" routerLink="/" *ngIf="bh?.id == count" [src]="bh?.src" height="42" width="42"/>

和我的.ts方法:

  Timer(){
  setInterval(() => {
    this.count=this.count++
  }, 2000)
}

with:

export class HeaderComponent implements OnInit{
count=0

BHs = [
  new Bh (1, "assets/img/photo_bonhommes/BH1.jpg.png"),
  new Bh (2, "assets/img/photo_bonhommes/BH2.png"),
  new Bh (3, "assets/img/photo_bonhommes/BH3.png"),
  new Bh (4, "assets/img/photo_bonhommes/BH4.png"),
  new Bh (5, "assets/img/photo_bonhommes/BH5.png"),
  new Bh (6, "assets/img/photo_bonhommes/BH6.png"),
  new Bh (7, "assets/img/photo_bonhommes/BH7.png"),
  new Bh (8, "assets/img/photo_bonhommes/BH8.png"),
  new Bh (9, "assets/img/photo_bonhommes/BH9.png"),
  new Bh (10, "assets/img/photo_bonhommes/BH10.png"),
  new Bh (11, "assets/img/photo_bonhommes/BH11.png"),
];
}

顺便说一句,它与* ngFor一起显示,但我想我必须在这里使用* ngIf。

我也尝试过:

<img id="bh" routerLink="/" *ngIf="bh?.id == this.count" [src]="bh?.src" height="42" width="42"/>

但不起作用。非常感谢!

html angular var
1个回答
0
投票

您的代码在大多数情况下看起来不错,我调整了一些位置。唯一可能出现的其他问题是错误的图片路径,它可能应该以'/assets/img/photo_bonhommes/BH1.jpg'开头,并且绝对不应有两个扩展名。另一个可能是您的Bh类构造函数创建了该类,但是您没有正确分配和公开ID。

export class HeaderComponent implements OnInit{
count=0

BHs = [
  new Bh(1, "/assets/img/photo_bonhommes/BH1.jpg"),
  new Bh(2, "/assets/img/photo_bonhommes/BH2.png"),
  new Bh(3, "/assets/img/photo_bonhommes/BH3.png"),
  new Bh(4, "/assets/img/photo_bonhommes/BH4.png"),
  new Bh(5, "/assets/img/photo_bonhommes/BH5.png"),
  new Bh(6, "/assets/img/photo_bonhommes/BH6.png"),
  new Bh(7, "/assets/img/photo_bonhommes/BH7.png"),
  new Bh(8, "/assets/img/photo_bonhommes/BH8.png"),
  new Bh(9, "/assets/img/photo_bonhommes/BH9.png"),
  new Bh(10, "/assets/img/photo_bonhommes/BH10.png"),
  new Bh (11, "/assets/img/photo_bonhommes/BH11.png"),
];
}
ngOnInit() {
 Timer(){
  setInterval(() => {
    this.count++
  }, 2000)
 }
}

--------------------HTML----------------
<ng-container *ngFor="let bh of BHs">
  <img id="bh" routerLink="/" *ngIf="bh.id === count" [src]="bh.src" height="42" 
   width="42"/>
</ng-container>
© www.soinside.com 2019 - 2024. All rights reserved.