添加到列表后,只有第一个新项目具有动画效果

时间:2018-12-20 13:33:46

标签: angular angular-animations

所以我的问题是我正在使用cdkVirtualFor添加,要在添加到列表中后为新项目设置动画。不幸的是,该列表仅在开始时才具有动画效果,并且在添加第一个元素之后才出现,而新条目只是不具有动画效果。

Stackblitz示例: https://stackblitz.com/edit/angular-cdc2ne

组件代码:

import { FixedSizeVirtualScrollStrategy, VIRTUAL_SCROLL_STRATEGY } from '@angular/cdk/scrolling';
import { ChangeDetectionStrategy, Component, ChangeDetectorRef } from '@angular/core';
import { trigger, transition, style, animate, query, stagger, animateChild } from "@angular/animations";

export class CustomVirtualScrollStrategy extends FixedSizeVirtualScrollStrategy {
  constructor() {
    super(50, 0, 0);
  }
}

/** @title Virtual scroll with a custom strategy */
@Component({
  selector: 'cdk-virtual-scroll-custom-strategy-example',
  styleUrls: ['cdk-virtual-scroll-custom-strategy-example.css'],
  templateUrl: 'cdk-virtual-scroll-custom-strategy-example.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
  providers: [{ provide: VIRTUAL_SCROLL_STRATEGY, useClass: CustomVirtualScrollStrategy }],
  animations: [
    trigger('items', [
      transition(':enter', [
        style({ transform: 'scale(0.5)', opacity: 0 }),  // initial
        animate('1s cubic-bezier(.8, -0.6, 0.2, 1.5)', 
          style({ transform: 'scale(1)', opacity: 1 }))  // final
      ])
    ]),
  ]
})
export class CdkVirtualScrollCustomStrategyExample {

  constructor(private cdRef: ChangeDetectorRef) { }
  items = Array.from({ length: 15 }).map((_, i) => `Item #${i}`);
  delete(i: number) {
    this.items = this.items.filter((a, index) => index !== i);
  }
  add() {
    this.items = ['Item #' + this.items.length, ...this.items];
    this.cdRef.detectChanges();

  }
}

查看:

    <cdk-virtual-scroll-viewport class="example-viewport">
  <div @items *cdkVirtualFor="let item of items; let i=index" class="example-item">{{item}}</div>
</cdk-virtual-scroll-viewport>
{{items.length | json}}
<button (click)="add()">ADD</button>

@Edit

好吧,实际上我已经解决了我的第一个问题。

https://stackblitz.com/edit/angular-36sqcf

但是现在我看到,如果相当快地添加新元素,则只有最后一个元素会正确设置动画。如何为所有元素设置动画?

0 个答案:

没有答案