【发布时间】:2019-02-08 12:39:16
【问题描述】:
我正在开发一个 Angular 6 应用程序(使用 Bootstrap)并创建了以下模板:
<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>
我想每次只显示一个新闻,所以*ngFor 循环中数组的每个项目都应该替换前一个,如果循环位于最后一个项目,它应该从第一个项目重新开始。
此外,最好在一个项目和下一个项目之间添加延迟。
数组如下所示:
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'},
]
您知道任何解决方案吗?
【问题讨论】:
-
我不认为你可以在 html 中这样做。您只需要一个 div 并更新模型。
-
您可以创建一个变量
currentItemIdx并定期更新它。例如:setInterval(()=>{this.currentItemIdx = (this.currentItemIdx + 1)%this.news.length;},1000)并在模板中去掉 ngFor 并使用 news[currentItemIdx] -
非常好的评论!如果您将其发布为答案,我将投票赞成!谢谢
标签: arrays angular loops delay ngfor