smartmouse
smartmouse

Reputation: 14404

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?

Upvotes: 1

Views: 514

Answers (2)

End
End

Reputation: 626

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

Upvotes: 1

Alan-Old
Alan-Old

Reputation: 128

Sorry for answer, can't add comment

Why not use $interval to do that? At each interval show an element of the array.

Upvotes: 0

Related Questions