0

I want to apply animation when click one particular div generated with *ngFor. Currently it applies to every div when clicks. How can I achieve this ?

   animations: [
trigger('changeDivSize', [
  state('initial', style({
    width: '30px',
    height: '30px',
    opacity: '0.5',
    margin: '10px'
  })),
  state('final', style({
    width: '32px',
    height: '32px',
    opacity: '1',
    margin: '10px'
  })),
  transition('initial<=>final', animate('200ms')),
  transition('final=>initial', animate('200ms'))
]),

]


  changeState() {
    this.currentState = this.currentState  === 'initial' ? 'final' : 'initial';
  }

    <div class="row">
      <div *ngFor="let group of groups" class="col-1">
      <div  (click)="changeState()" [@changeDivSize]=currentState  [ngStyle]="{'background-color': group.colorCode}"></div>
    </div>
Thilina Akalanka
  • 163
  • 1
  • 14

2 Answers2

2

You can use the index of your elements with the *ngFor to have a separate currentState value for each element, so animation works on individual elements.

  <div *ngFor="let group of groups;let i = index" class="col-1">
    <div  (click)="changeState(i)" 
          [@changeDivSize]=group.currentState  
          [ngStyle]="{'background-color': group.colorCode}">
    </div>
  </div>

  public changeState(index: number): void {
      console.log(index)
      this.groups[index].currentState = 
          (this.groups[index].currentState  === 'initial') ? 'final' : 'initial';
  }
Daniel
  • 286
  • 1
  • 2
  • 9
Ininiv
  • 1,325
  • 7
  • 12
1
 changeState(index) {
    this.currentState[index] = this.currentState[index]  === 'initial' ? 'final' : 'initial';
  }

Better Take array of currentState of each item of group as above.

Then use currentState[i] for individual element of groups.

<div class="row">
   <div *ngFor="let group of groups, index as i" class="col-1">
   <div  (click)="changeState(i)" [@changeDivSize]=currentState[i]  [ngStyle]="{'background-color': group.colorCode}"></div>
</div>

Hope this helps.

Chintan Joshi
  • 1,207
  • 1
  • 9
  • 17