angular - 动态创建 Angular 动画

标签 angular ng-animate angular-animations

我正在创建一个分页组件,它可以滑动到下一个或上一个全屏页面。因为不同浏览器和设备的问题,我暂时放弃了只使用 CSS 过渡。我有一个有效的 Angular 动画解决方案,但新问题是它无法缩放。

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  animations: [
    trigger('slideTransition', [
      state('firstPage', style({ transform: 'translateX(0)' })),
      state('secondPage', style({ transform: 'translateX(-100%)' })),
      transition('firstPage=>secondPage', animate('0.6s ease')),
      transition('secondPage=>firstPage', animate('0.6s ease'))
  ])]
})
export class AppComponent {

  state = 'firstPage';

  nextPage() {
    this.state = 'secondPage';
  }

  previousPage() {
    this.state = 'firstShowing';
  }

}

问题是,如您所见,当我有 9 页时。我不想定义 9 个状态和 18 个转换。如何根据页数执行可重用状态或生成状态和转换运行时?有什么想法吗?

模板看起来像这样

<div class="container">
  <div [@slideTransition]="state" class="page">
    <h1>Page 1</h1>
    <div class="clicker" (click)="nextPage()">clickity</div>
  </div>
  <div [@slideTransition]="state" class="page">
    <h1>Page 2</h1>
    <div class="clicker" (click)="previousPage()">clackity</div>
  </div>
</div>

最佳答案

您需要的是向状态发送params。这可以通过添加类(class)成员并根据您的页码不断更新来实现。然后将其连接到您的 HTML 中。

现在以下是您现有代码的潜在补充:

animations: [
  trigger('slideTransition', [
    // ...
    state('*',
          style({ marginLeft: '{{pageMarginValue}}%' }), 
          {params: {pageMarginValue: 0}}),
    transition('*=>*', animate('0.6s ease')),
    // ...
])

]

然后把它添加到你的类中:

export class AppComponent {
  // ...
  private currentMargin = 0;
  private step = 10; // replace with actual value

  next(): void { this.currentMargin += this.step; }
  previous(): void { this.currentMargin -= this.step; }

  // ...
}

在您的 HTML 中,像这样传递 currentMargin:

<div [@slideTransition]="{value: state, params: { pageMarginValue: currentMargin }}"></div>

关于angular - 动态创建 Angular 动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44323258/

相关文章:

angular - Hook 以从 Typescript 引导 4 模态显示/隐藏事件

javascript - 卡片翻转过渡在 IE 中无法正常工作

css - 使用 ng-animate 时偏移占位符元素的正确方法是什么?

css - Angular ng-重复动画一次

css - Angular - 列表元素的交错动画

css - angular2-忙不显示动画-Angular 4

css - Angular 5 : fade animation during routing (CSS)

Angular 通用 + PM2 : Keeps exiting and restarting

html - 在 Angular 中选择时如何检索 id 和名称?

node.js - 如何以 Angular 4在帖子正文中发送数据