首页 > 解决方案 > Angular 6 组件对来自其他组件的 setTimeout 做出反应

问题描述

我正在用 Angular 6 编写一个网站。我有两个组件,slideshowproduct-list.

在我的幻灯片组件中,我有一个 setTimeout。

public carousel() {
  var i;
  var y = document.getElementsByClassName("mySlides");
  for (i = 0; i < y.length; i++) {
     y[i].setAttribute("style", "none"); 
  }
  this.curIndex++;
  if (this.curIndex > y.length) {this.curIndex = 1}   
  y[this.curIndex-1].setAttribute("style", "display:block;");
  this.timer = setTimeout(() => {
    this.carousel();
  }, 4000);
}

它改变了我幻灯片中的图像。如您所见,它每 4 秒发生一次。

现在到目前为止,这是预期的行为。

在我的产品列表组件中,我有一个随机颜色生成器。

getBackground (bg) {
    const color = this.color(0.5);
    return this._sanitizer.bypassSecurityTrustStyle(`
    background: -moz-linear-gradient(top, ${color} 0%, ${color} 100%), url(${bg}) repeat 0 0;

background: -moz-linear-gradient(top, ${color} 0%, ${color} 100%), url(${bg}) repeat 0 0;

background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,${color}), color-stop(100%,${color})), url(${bg}) repeat 0 0;

background: -webkit-linear-gradient(top, ${color} 0%,${color} 100%), url(${bg}) repeat 0 0;

background: -o-linear-gradient(top, ${color} 0%,${color} 100%), url(${bg}) repeat 0 0;

background: -ms-linear-gradient(top, ${color} 0%,${color} 100%), url(${bg}) repeat 0 0;

background: linear-gradient(to bottom, ${color} 0%,${color} 100%), url(${bg}) repeat 0 0;
    `);

  }

这将返回具有随机颜色渐变的样式。

在这里,它在我的产品列表组件中被调用

 <div class="rows"  style="text-align: center">
<div *ngFor="let product of products; let i = index">


    <div  class="col-md-4 col-xs-6 clear product-list-item" title="{{product.product_name}}"  routerLink="/product/{{product.product_id}}" [style]="getBackground('https://financialtribune.com/sites/default/files/field/image/17january/04-zs-ice-cream_66-ab.jpg')">
    <div class="product-list-item-title">
      <h1>{{product.product_name}}</h1>

    </div>
    <br>
    <img class="product-list-item-image" src={{product.product_image_url}}> &nbsp;
    <div class="product-list-item-description">
      <h3>{{product.product_description}}</h3>

    </div>

    <div class="clear visible-lg" *ngIf="(i + 1) % 6 == 0"></div>
    <div class="clear visible-md" *ngIf="(i + 1) % 4 == 0"></div>
    <div class="clear visible-sm" *ngIf="(i + 1) % 3 == 0"></div>
    <div class="clear visible-xs" *ngIf="(i + 1) % 2 == 0"></div>

  </div>




</div>
</div>

但问题是,每次幻灯片改变时,我的颜色也会改变。

我怎样才能让它不会改变任何东西?当幻灯片更改为新图片时,颜色会完全改变,所以我认为这是因为设置超时。

标签: javascriptangularangular6

解决方案


正如它所写的,每次元素发生变化时都应该调用 getBackground() 。但是,如果您将样式设置为属性值并在 ngOnInit() 中启动它,它不会改变。创建一个包含产品颜色的数组:

<div *ngFor="let product of products; let i = index">
...

   <div  class="col-md-4 ...[style]="bg[i]">
    ...

打字稿:

bg = [];
ngOnInit(){
    this.products.map(item => this.bg.push(this.getBackground('https://financialtribune.com/sites/default/files/field/image/17january/04-zs-ice-cream_66-ab.jpg'))
    }
}

推荐阅读