angular - Angular 4 中的动画路线

标签 angular

我正在尝试以 Angular 4 设置路由转换动画,动画在页面首次加载和页面刷新时有效,所以我知道动画有效,但在我切换路由时无效。我错过了什么?

这是代码...

//组件元数据

animations: [fadeInAnimation]

//模板

<div class="route-container" [@fadeInAnimation]>
    <router-outlet></router-outlet>
</div>

//样式

.route-container {
  position:relative;
}
.route-container>* {
  display:block;
}

//动画

trigger('fadeInAnimation', [

    // route 'enter' transition
    transition(':enter', [

        // css styles at start of transition
        style({ opacity: 0 }),

        // animation and styles at end of transition
        animate('6s cubic-bezier(.35,0,.25,1)', style({ opacity: 1 }))
    ]),
]);

最佳答案

为了确保路由动画在每条路线上进行,您需要定义每条路线之间的过渡。以下是我在“home”路由和“acct”路由之间转换时用来创建抽屉效果的示例:

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

export const baseAnimation =
    trigger('baseAnimation', [
      transition('acct => home', [
        query(':enter, :leave', style({ position: 'absolute', top: 0, left: 0, right: 0 })),
        query(':leave', style({ height: '*'})),
        query('.acct', [
            animate('300ms',
            style({ height: 0 }))
        ])
      ]),
      transition('home => acct', [
        query(':enter, :leave',
          style({ position: 'absolute', top: 0, left: 0, right: 0 })),
        query(':enter .acct', [
          style({ height: 0 }),
          animate('300ms', style({ height: '*' }))
        ])
      ])
    ])

请注意,.acct 指的是帐户页面路由的类标签,您的应用程序可能不需要(或可能需要相应更改)。通过这种方式,您可以在路线更改时为每条路线的子元素设置动画。

我在我的 app.component.html 中使用了一个函数来处理路由动画:

<div [@baseAnimation]="prepareRouteTransition(outlet)">
  <router-outlet #outlet="outlet"></router-outlet>
</div>
</div>

app.component.ts 应该加载动画并为路由声明动画:

import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { baseAnimation } from './anim/base.animation';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
  animations: [ baseAnimation ]
})

export class AppComponent {

  constructor() { }

  prepareRouteTransition(outlet) {
    const animation = outlet.activatedRouteData['animation'] || {};
    return animation['value'] || null;
  }
}

关于angular - Angular 4 中的动画路线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45639268/

相关文章:

angular - 如何将 bool 主题的值初始化为 false?

Angular 6.4.1 环境构建不起作用

angular - 大于 Angular Validator 中的跨域验证

html - 如何垂直对齐文本列表中的所有元素?

angular - 有没有办法防止 formControl 触发事件?

angular - 如何在模板上显示包含 html 内容的 typescript 字符串变量作为元素,而不是字符串?

javascript - Angular 列表引用在项目删除时未更新

javascript - Angular 2 外部库错误

Angular - 在 ngFor 内的 ngIf 内带有参数的 ng-template

forms - Angular 2 : Apply remote validation errors to form