假设我有这段代码:
<div id="parent">
<div class="child">
<div class="child">
<div class="child">
</div>
我想要开始自动将active
类添加到第一个子类中。之后,我希望每 X 秒切换到 active
类的下一个子级。 Angular 2 可以做到这一点吗?
最佳答案
您可以使用如下模板动态地将类和项目添加到列表中:
<div id="parent">
<div *ngFor="let item of items; let i = index"
class="child" [class.active]="activeIndex === i">
{{item}}
</div>
</div>
与支撑组件:
export class AppComponent {
activeIndex = 0;
items = ['item 1', 'item 2', 'item 3']
ngOnInit() {
setInterval(_ => {
this.activeIndex++;
if (this.activeIndex >= this.items.length){
this.activeIndex = 0;
}
}, 500)
}
addItem() {
this.items.push('item ' + (this.items.length + 1));
}
}
关于javascript - 使用 Angular 2 在兄弟元素之间切换类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38014586/