Ke Vin
Ke Vin

Reputation: 3750

How do angular 4 animation transition the routeroutlet properly?

Here is what i trying to achieve, i want an transition that slide to left and right when change my page, but my code it's not working, the event already triggered then when i scroll my page it trigger so many event (i test it with console.log)

here is how my code looks like

app.component.html :

<main [@routerTransition]="getRouterOutletState(o)">
  <router-outlet #o="outlet"></router-outlet>
</main>

and here is my app.component.ts :

animations: [
    trigger('routerTransition', [
      state('in', style({ transform: 'translateX(0)' })),
      transition('out => in', [
        style({ transform: 'translateX(-100%)' }),
        animate(400)
      ]),
      transition('in => out', [
        animate(400, style({ transform: 'translateX(100%)' }))
      ])
    ]),
  ]

})


export class AppComponent {
    fadePageInOut: string = 'in';

  getRouterOutletState(outlet) {
    console.log(outlet + " event triggered outlet");
    this.fadePageInOut = (this.fadePageInOut === 'in' ? 'out' : 'in');
  }

}

why it's not working? what i missed here? and console.log of the result of my code is like this :

enter image description here

the event increase when i scroll my page up and down, i must do something wrong for the event triggering and still the transition wont work

Upvotes: 2

Views: 1134

Answers (2)

Aamir Khan
Aamir Khan

Reputation: 3031

You are not returning any value from the getRouterOutletState() function. As a result the animation is not triggered. Add a return statement from the getRouterOutletState() function and return the current value of fadePageInOut.

getRouterOutletState(outlet) {
  console.log(outlet + " event triggered outlet");
  this.fadePageInOut = (this.fadePageInOut === 'in' ? 'out' : 'in');

  return this.fadePageInOut; // <-- Add this line
}

Useful link for Angular Route Animations: https://medium.com/google-developer-experts/angular-supercharge-your-router-transitions-using-new-animation-features-v4-3-3eb341ede6c8

Upvotes: 1

P.S.
P.S.

Reputation: 16384

The main issue is in your animation controller: you should bind it to property with animation state, not to method, like this:

<main [@routerTransition]="fadePageInOut">

May be there are some more issues, I can't really say without live example, but I think this change should do the trick.

And the animation will fire only when you change the state from "out" to "in" and vise versa, so it seems like you also should change this:

transition('out => in', [

to this:

transition('* => in', [

Upvotes: 1

Related Questions