Angular 4 Animation won't trigger on route change

为君一笑 提交于 2019-12-08 12:13:46

问题


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:


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.



来源:https://stackoverflow.com/questions/46238275/angular-4-animation-wont-trigger-on-route-change

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