【问题标题】:How to get .ts var value in *ngIf HTML?如何在 *ngIf HTML 中获取 .ts var 值?
【发布时间】:2019-10-16 09:59:37
【问题描述】:

我试图在 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)
}

与:

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"/>

但不工作..非常感谢!

【问题讨论】:

  • bh 来自哪里?
  • this.count 应该是 count,但我认为更改不会解决您的问题。
  • 对不起,我会添加它
  • 好的,谢谢@TheNsn666,这是第一次帮助

标签: html angular var


【解决方案1】:

您的代码大部分看起来都不错,我调整了一些地方。唯一可能的更多问题是错误的图片路径,它可能应该以“/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>

【讨论】:

  • 谢谢,我考虑过添加 ngFor AND ngIf 但没有那样做。它也不会让我在 ngOnInit 中添加计时器。我在 Timer 上出现错误说“;”预计.. ngOnInit() { this.loginService.loginText.subscribe( login => (this.login = login) ) Timer(){ setInterval(() => { this.count=this.count++ }, 2000) } }
  • @Skimar 这可能是因为您缺少分号。 ngOnInit() { this.loginService.loginText.subscribe(login =&gt; this.login = login); this.timer(); } timer() { setInterval(() =&gt; { this.count++ }, 2000); } 如果你把它放在组件中,这在技术上应该可以工作
猜你喜欢
  • 2022-11-23
  • 1970-01-01
  • 2021-02-05
  • 1970-01-01
  • 1970-01-01
  • 2019-09-19
  • 1970-01-01
  • 2021-03-18
  • 1970-01-01
相关资源
最近更新 更多