新呈现元素的动画,但不在页面加载时

Animation for newly rendered elements, but not on page load

我订阅了 Firebase 实时数据库,因此当我向它提交内容时,它会立即呈现在视图中,而无需 jQuery 或 ajax。

我想为这些元素的渲染设置动画,这样当一个新元素被添加到 DOM 时,它的 divbackground-color 是绿色的并慢慢消失离开。我不希望此 class 的所有 div 都在加载时执行此动画。

我知道前者怎么做:

@keyframes green-fade {
    0% {background: rgb(173, 235, 173);}
    100% {background: none;}
}

.post-div {
   animation: green-fade 5s ease-in 1;
}

当然,这个动画会在 class 渲染的任何时候发生,包括加载时。

我对 "Angular 2 way" 感兴趣。

添加一个触发器,用于检查项目通过网络时的状态。当 itemStatenew.

时,我在这里触发动画

    trigger('itemState', [
      transition('* => new', animate(5000, keyframes([
        style({ backgroundColor: 'red', offset: 0 }),
        style({ backgroundColor: '*', offset: 1.0 })
      ]))),

为您的触发器提供对项目状态的引用,并在动画结束时将其设置为 null。

<div [@itemState]="someItem.itemState" (@itemState.done)="someItem.itemState=''">

请务必在您的帖子中添加 itemState 属性,以便您可以将它们标记为新帖子!

您可以使用生命周期钩子 AfterViewInit 在初始视图渲染完成后激活动画。

https://embed.plnkr.co/5l1kf5lMLEXSE8pNzqik/

@Component({
  selector: 'my-app',
  template: `
    <div *ngFor="let item of items" [@greenFade]="animate ? 'in' : null">
      {{item}}
    </div>

    <button (click)="addItem()">add</button>
  `,
  animations: [
    trigger('greenFade', [
      transition('void => in', [style({background: 'rgb(173, 235, 173)'}), animate('5s ease-in')])
    ])
  ]
})
class App implements AfterViewInit {
  constructor(private cdRef: ChangeDetectorRef){}

  items: String = ['Item','Item','Item'];
  addItem(){
    this.items.push('Item');
  }

  animate: boolean;
  ngAfterViewInit(){
    this.animate = true;
    this.cdRef.detectChanges();
  }
}

从 Angular 4.25 开始,有一种更简单的方法可以做到这一点:如果您想在视图初始化时抑制 :enter 动画,只需用以下动画包装它:

template: `
  <div [@preventInitialChildAnimations]>
    <div [@someAnimation]>...</div>
  </div>
`,
animations: [
  trigger('preventInitialChildAnimations', [
    transition(':enter', [
      query(':enter', [], {optional: true})
    ])
  ]),
  ...
]

最简单的解决方案:

 @Component({
    selector: 'myComponent',
    template: '<div [@.disabled]="disableAnimations" [@someAnimation]="someValue">',
    animations: [trigger('someAnimation', [transition('* => *', [style({ transform: 'scale(1.1)' }), animate(250)])])]
})
export class MyComponent implements AfterViewInit {

    disableAnimations: boolean = true;

    constructor() {}

    ngAfterViewInit(): void {
        this.disableAnimations = false;
    }
}

参考: https://angular.io/api/animations/trigger (滚动到 "disable animations")