简体   繁体   中英

Angular 4 Animate list item by item

I wish to animate a list ul > li item by item.

It's OK when query :enter , but I need to animate the :leave state before the :enter when list elements change, how can I do that?

Follow my actual code:

@Component({
  selector: 'ng-list',
  templateUrl: './ng-list.component.html',
  encapsulation: ViewEncapsulation.None,
  animations: [

    trigger('listAnimation', [
      transition('* => *', [

        query(':enter', style({ opacity: 0 }), { optional: true }),

        query(':enter', stagger('300ms', [
          animate('1s ease-in', keyframes([
            style({ opacity: 0, transform: 'translateY(-75%)', offset: 0 }),
            style({ opacity: .5, transform: 'translateY(35px)', offset: 0.3 }),
            style({ opacity: 1, transform: 'translateY(0)', offset: 1.0 }),
          ]))]), { optional: true })

      ])
    ])

  ]
})
export class NgListComponent {

  items: Array<any>;
  animateItems = false;

  constructor() {
    this.items = new Array<INgxSidemenuItem>();
  }

  selectMenu(item: INgxSidemenuItem) {
    this.animate();

    // ...
  }

  private animate() {
    this.animateItems = !this.animateItems;
  }

}
<div [@listAnimation]="animateItems">
  <div class="menu-item" *ngFor="let item of items (click)="selectMenu(item)">
    <a (click)="selectMenu(item)">{{ item.title }}</a>
  </div>
</div>

You are not supposed to query ':enter' . :enter is just a shorthand for void => * meaning it can be used in a transition() to declare between what states the transition regards. What you want is to query a selector. Since query() uses document.querySelectorAll() behind the scenes, you can use any CSS selector to get select the elements that you want to stagger. What you therefore want to do is to query the divs, either by just the tag or by the class name. For example, using the class name:

trigger('listAnimation', [
  transition('* => *', [

    query('.menu-item', style({ opacity: 0 }), { optional: true }),

    query('.menu-item', stagger('300ms', [
      animate('1s ease-in', keyframes([
        style({ opacity: 0, transform: 'translateY(-75%)', offset: 0 }),
        style({ opacity: .5, transform: 'translateY(35px)', offset: 0.3 }),
        style({ opacity: 1, transform: 'translateY(0)', offset: 1.0 }),
      ]))]), { optional: true })

  ])
])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM