user2924127
user2924127

Reputation: 6242

not looping when in interval

I have some html which looks like this:

           <li *ngFor="#item of items; #i=index" >
            <h2>{{ item }}</h2>
            </li>

I then want to populate the list every one second, so I have something like this:

let t=setInterval(() =>{
                this.items  = ["a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9"];
            },1000);

I know looking at this it looks like why are you running an interval the value is the same. I have other logic in my code which has if and else statements that will break the interval, but I am not getting any items displaying at all and that is my concern. I expect the 9 items to be in a list on my html page, but none of them display. If I remove the interval then it displays the items. So if it is inside the interval it does not display, how can I make it so it does? I am unsure of the problem.

Upvotes: 0

Views: 50

Answers (2)

drew moore
drew moore

Reputation: 32670

A more "Angular 2 way" of approaching this would be to use AsyncPipe in conjunction with an Observable and the Observable.timer operator:

@Component({
  selector: 'foo',
  pipes: [AsyncPipe], //import this from angular2/common
  template: `
    <ul>
      <li *ngFor="#item of (items | async); #i=index" >
        <h2>{{ item }}</h2>
      </li>
    </ul>
  `
})
class YourComponent {
   items: Observable<string[]>; 

   constructor(){
       this.items = Observable.timer(0, 1000) //emit after 0 ms, then every 1000ms 
                              .map(()=>{
                                  //insert real business logic
                                  return  ["a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9"]
                               })
   }

} 

Upvotes: 2

user2924127
user2924127

Reputation: 6242

https://angular.io/api/core/ChangeDetectorRef

ChangeDefectorRef did it for me. Adding this.ref.markForCheck(); inside of the interval refreshed the items for me and it now displays.

Upvotes: 0

Related Questions