Eliya Cohen Eliya Cohen - 5 months ago 15
AngularJS Question

Switch classes between siblings elements with Angular 2

Let's say I have this code:

<div id="parent">
<div class="child">
<div class="child">
<div class="child">
</div>


I want for a start to add automatically to the first child the class
active
. After that, I want for each X seconds to switch to the next child the
active
class. Is it possible to do this with Angular 2?

Answer

Working Example

You can dynamically add a class and items to a list with a template like this:

<div id="parent">
  <div *ngFor="let item of items; let i = index"
    class="child" [class.active]="activeIndex === i">
    {{item}}
  </div>
</div>

With the supporting component:

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));
  }
}