IkePr
IkePr

Reputation: 930

Angular change img src on timeout

In my html I have:

<img src="{{activeImage}}" class="img-fluid img-file img-center-style">

In the .ts, activeImage is defined with a default value:

  promotions: any = [];
  activeImage: string = 'assets/Promo_1.jpg';

Now in the ngOnInit method I call a service which returns the following and sets it in promotions: enter image description here

What is my goal:

To change the activeImage to the value of file in commercial_file array. (It always has one element - 0). Then after a period of time, it changes the value to the second file in array.

Here is what I tried:

  ngOnInit() {
    this.mainService.getPromotion().subscribe(promotions => {
      console.log("getPromotion from servise are ", promotions);
      this.promotions = promotions;

      //If there is something, call method setActiveImage and send array
      if (this.promotions.length > 0) {
        this.setActiveImage(this.promotions);
      }

    });

  }

  setActiveImage(promotions) {
    for (let i = 0; i <= promotions.length - 1; i++) {
      console.log("one promotion is: ", promotions[i]);
      setTimeout(function () {
      //SET SRC TO FILE FROM PROMOTIONS
        this.activeImage = 'http://myurl.com/public/Commercials/' + promotions[i].commercial_file[0].file;
      }, 3000);

    }
  }

The img src should have file value for 3s, then change to the second image value. But that does not happen, it just shows the default value defined at the beginning (assets/Promo_1.jpg).

Now if I set this in ngOnInit without any setTimeout or anything, it works fine and it sets the picture well:

this.activeImage = 'http://myurl/public/Commercials/' + this.promotions[0].commercial_file[0].file;

StackBlitz: https://stackblitz.com/edit/angular-5fteig?file=src%2Fapp%2Fapp.component.ts

TLDR: Change img src on 3s with data gathered from server.

Upvotes: 0

Views: 1568

Answers (1)

Shub
Shub

Reputation: 2704

use arrow function or bind this to the function if you need to access this

setTimeout(()=> {
    //SET SRC TO FILE FROM PROMOTIONS
    this.activeImage = 'http://myurl.com/public/Commercials/' + promotions[i].commercial_file[0].file;
}, 3000);

Also in your example, you need get instance of service in your constructor before using it, and import it as well if your editor doesn't does that automatically.

constructor(private mainService : mainService){}

Edit:

To change images every 3 seconds set timer with incremental values:

setActiveImage(promotions) {
    for (let i = 0; i <= promotions.length - 1; i++) {
      console.log("one promotion is: ", promotions[i]);
      setTimeout( ()=> {
      //SET SRC TO FILE FROM PROMOTIONS
        this.activeImage = 'http://myurl.com/public/Commercials/' + promotions[i].commercial_file[0].file;
      }, 3000*(i+1)); //Change i+1 to i if you don't want delay for 1st image.
    }
}

Upvotes: 3

Related Questions