Search code examples
arraysangularloopsdelayngfor

How to change the content of the same HTML element at every item in an ngFor loop (with delay)?


I'm developing an Angular 6 app (with Bootstrap) and I have created the following template:

<div class="news-container">
    <div class="new" *ngFor="let n of news">
        <div class="date">{{n.date}}</div>
        <div class="text">{{n.text}}</div>
    </div>
</div>

I would like to show only one news per time, so every item of the array in the *ngFor loop should replace the previous one, and if the loop is at the last item it should restarts from the first item again.

In addition, it would be nice to add a delay between an item and the next one.

Here is how the array looks like:

news: [
    {id: 1, date: '01-01-2018', text: 'this is a news'},
    {id: 2, date: '01-01-2018', text: 'this is another news'},
    {id: 3, date: '01-01-2018', text: 'breaking news'},
    {id: 4, date: '01-01-2018', text: 'foo bar'},
]

Do you know any solution to reach that?


Solution

  • You can use a setTimeout() to delay the news items that are displayed and then with a recursive function loop through all the news and start over again. Here is a stackblitz I created with the answer: https://stackblitz.com/edit/angular-bdpkbw