首页 > 解决方案 > 如何在Angular中的时间间隔后更改图像?

问题描述

所以我有一个图像,我有一些计数器。在计数器总数超过 500 之后,我想显示另一个图像。

所以我有这个模板:

  <img src="./assets/noun_Arrow_green.png" alt="Forest" style="width: 50%" />

并且该图像必须在计数器高于 500 后使用此图像进行更改:

<img src="./assets/noun_Arrow_red.png" alt="Forest" style="width: 50%" />

这是我拥有的 ts 脚本:

counters = [100, 200, 10];

increaseTime() {
    this.counters.forEach(() => {
      setInterval(() => {
        this.counters[0]++;
        this.counters[1] = this.counters[1] + 10;
        this.counters[2] = this.counters[2] + 17;

        if (this.counters[0] + this.counters[1] + this.counters[2] > 500) {
          clearInterval();
        }
      }, 3000);
    });
  }

但我必须改变什么?

谢谢

标签: javascripthtmlangulartypescript

解决方案


src在组件中创建一个参数

imageSource:string="./assets/noun_Arrow_green.png"

在 html 中给出这个参数

  <img [src]="imageSource" alt="Forest" style="width: 50%" />

然后在间隔更改此参数

increaseTime() {
    this.counters.forEach(() => {
      setInterval(() => {
        this.counters[0]++;
        this.counters[1] = this.counters[1] + 10;
        this.counters[2] = this.counters[2] + 17;
        
        if (this.counters[0] + this.counters[1] + this.counters[2] > 500) {
          clearInterval();
          this.imageSource="./assets/noun_Arrow_red.png"
        }
      }, 3000);
    });
  }

推荐阅读