Angular 4 Animation won't trigger on route change

1.5k Views Asked by At

I've created the following animation in my Angular 4 project:

import { trigger, state, style, transition, animate } from '@angular/animations';

export function slide() {
    return trigger('slide', [
            transition('void => *', [
                style({opacity: 0}),
                style({transform: 'translateX(100%)'}),
                animate('1s ease-in-out', style({transform: 'translateX(0%)', opacity: 1}))
            ]),
            transition('* => void', [
                style({opacity: 0}),
                style({transform: 'translateX(100%)'}),
                animate('1s 2s ease-in-out', style({transform: 'translateX(0%)', opacity: 1}))
            ])
        ])
  }

I've attached the animation to my component using the host property of the @Component decorator.

@Component({
  selector: 'test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.scss'],
  animations: [slide()],
  host: {'[@slide]': '', 'style': 'display: block;'}
})

Now, I'd expect the animation to trigger at two points: 1. When the component is initialized, a.k.a when I hit the appropriate route 2. When I leave that route and navigate to another one

The first scenario works flawlessly, however the second one doesn't. What am I missing/doing wrong here?

1

There are 1 best solutions below

0
On BEST ANSWER

I managed to get something similar to your animation working after some trial and error.

export function slideLeft() {
    return slide();
}

function slide() {
    return trigger('slide', [
        state('void', style({position:'absolute', width:'100%'}) ),
        state('*', style({position:'absolute', width:'100%'}) ),
        transition('void => *', [
            style({transform: 'translateX(100%)', opacity: 0 }),
            animate('1s ease-in-out', style({transform: 'translateX(0%)', opacity: 1 }))
        ]),
        transition('* => void', [
            style({transform: 'translateX(0%)', opacity: 1 }),
            animate('1s ease-in-out', style({transform: 'translateX(-100%)', opacity: 0 }))
        ])
    ]);
}

This is my animation code.

@Component({
  selector: 'app-away',
  templateUrl: './away.component.html',
  styleUrls: ['./away.component.css'],
  animations: [ slideLeft() ],
  host: { '[@slide]': '' }
})

This is how I applied it to the component.

For the leaving animation, you have used the exact same properties for the entering animation. What you want is for the component you are animating to move from 0% to -100% on leaving.

I also added some state helper functions, which apply a style of position: absolute to take your component out of the normal flow of the page.

Hope this helps.