Animation for newly rendered elements, but not on page load

耗尽温柔 提交于 2019-12-04 08:33:58

Since Angular 4.25 there's an easier way to do this: If you want to suppress an :enter animation on view initialization, just wrap it with the following animation:

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

Add a trigger that checks the state of a item when it comes through the network. Here I'm triggering the animation when itemState is new.

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

Give your trigger a reference to the state of your item, and set it to null when the animation finishes.

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

Be sure to add an itemState property to your posts so that you can flag them as new!

You can use the life cycle hook AfterViewInit to activate the animation after the initial view rendering has finished.

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

Easiest solution:

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

Reference: https://angular.io/api/animations/trigger (scroll to "disable animations")

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!