Angular - stagger animation for list elements

1.3k views Asked by At

I have a transition defined like this:

transition('show-content => hide-content', [
    query('.project-view-item', [
        style({
            opacity: 1,
            transform: 'translateX(0px)'
        }),
        stagger('0.3s', [
            animate(
                '0.2s',
                keyframes([
                    style({
                        opacity: 0,
                        transform: 'translateX(-40px)',
                        offset: 1
                    })
                ])
            )
        ])
    ])
])

Everything works as expected. The items go to left and fade-out. The problem is that after all items becomes hidden the style is reset and they become visible again all at once. It's like I need to have that css3 property called animation-fill-mode: forwards.

How can I do that in angular ? How can I retain last state of animation ?

Plnkr https://plnkr.co/edit/te0tJ76GkhkaRxF2LI2B

2

There are 2 answers

3
Vega On BEST ANSWER

Animation start and animation done will help here:

HTML

    <div class="project-view" (@content.start)="start($event)" 
    (@content.done)="done($event)" [@content]="isShowContent ? 'show-content': 'hide-content'">
        <div class="myClass">
            <div class="project-view-item">Hello</div>
            <div class="project-view-item">Hi</div>
            <div class="project-view-item">Hello</div>
            <div class="project-view-item">Hi</div>
            <div class="project-view-item">Hello</div>
            <div class="project-view-item">Hi</div>
            <div class="project-view-item">Hello</div>
            <div class="project-view-item">Hi</div>
        </div>
    </div>

Typescript:

  hideContent(callback?) {
    console.log("HIDE CONTENT CALLED");
    this.isShowContent = false;
    this.callback = callback;
  }

  showContent(callback?) {
    console.log("SHOW CONTENT CALLED");
    this.isShowContent = true;
    this.callback = callback;
  }

  done(event) {
    if (this.isShowContent) {
      document.querySelector('.myClass').setAttribute('style',
        "opacity:1;transform: 'translateX(0)')");
    }
    else {
      document.querySelector('.myClass').setAttribute('style',
        "opacity:0;transform: 'translateX(-40px)')");
    }

  }

  start(event) {
    document.querySelector('.myClass').setAttribute('style',
      "opacity:1; transform: 'translateX(-40px)')");
  }

Demo

2
shinigamiCz On

Also it is possible to add state declaration to your animations so you would not need to pollute your templates and ts files with animation logic:

transition('show-content => hide-content', [
    ....
]
state('hide-content', style({opacity: 0})),