带有 *ngFor 的角度动画仅适用于单击的值,而不是所有元素



我想在单击使用 *ngFor 生成的一个特定div 时应用动画。目前,它适用于点击时的每个div。我怎样才能做到这一点?

   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>

您可以将元素的索引与 *ngFor 一起使用,以便为每个元素提供单独的 currentState 值,以便动画适用于单个元素。

  <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';
  }
 changeState(index) {
    this.currentState[index] = this.currentState[index]  === 'initial' ? 'final' : 'initial';
  }

最好像上面一样获取组每个项目的当前状态数组

然后对组的单个元素使用 currentState[i]。

<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>

希望这有帮助。

相关内容

最新更新