Home > Web Front-end > JS Tutorial > body text

An in-depth analysis of how to use animation in Angular

青灯夜游
Release: 2021-09-26 10:45:03
forward
2118 people have browsed it

This article will introduce you to Angular animation, I hope it will be helpful to you! !

An in-depth analysis of how to use animation in Angular

1. State

1.1 What is state

State represents the appearance of elements to be moved at different stages of movement style. [Related tutorial recommendations: "angular tutorial"]

An in-depth analysis of how to use animation in Angular

1.2 Types of status

In Angular , there are three types of status, namely: void, *, custom

An in-depth analysis of how to use animation in Angular

##void: This state occurs when an element has been created in memory but has not yet been added to DOM or removed from DOM

*: The state after the element is inserted into the

DOM tree, or the state of the element already in the DOM tree, also called the default state

custom: Custom state, the element is on the page by default, and moves from one state to another, such as folding and expanding the panel.

1.3 Entry and exit animation

Entry animation means that the element appears in front of the user in the form of animation after it is created. The state of the entry animation is

void => * means, the alias is :enter

An in-depth analysis of how to use animation in Angular

The exit animation refers to a farewell animation executed before the element is deleted, the status of the exit animation Use

* => void, the alias is :leave

An in-depth analysis of how to use animation in Angular

2. Get started quickly

is in use Before the animation function, you need to introduce the animation module, that is,

BrowserAnimationsModule

import { BrowserAnimationsModule } from "@angular/platform-browser/animations"

@NgModule({
  imports: [BrowserAnimationsModule],
})
export class AppModule {}
Copy after login

default code analysis,

todo deleting tasks and adding tasks

<!-- 在 index.html 文件中引入 bootstrap.min.css -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" />
Copy after login
<div class="container">
  <h2>Todos</h2>
  <div class="form-group">
    <input (keyup.enter)="addItem(input)" #input type="text" class="form-control" placeholder="add todos" />
  </div>
  <ul class="list-group">
    <li (click)="removeItem(i)" *ngFor="let item of todos; let i = index" class="list-group-item">
      {{ item }}
    </li>
  </ul>
</div>
Copy after login
import { Component } from "@angular/core"

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styles: []
})
export class AppComponent {
  // todo 列表
  todos: string[] = ["Learn Angular", "Learn RxJS", "Learn NgRx"]
  // 添加 todo
  addItem(input: HTMLInputElement) {
    this.todos.push(input.value)
    input.value = ""
  }
  // 删除 todo
  removeItem(index: number) {
    this.todos.splice(index, 1)
  }
}
Copy after login

create animation

  • trigger method is used to create animation, specify the animation name

  • transition method is used to Specify the motion state of the animation, exit animation or entry animation, or customize the state animation.

  • style The method is used to set the style corresponding to the element in different states

  • animate Method is used to set motion parameters, such as animation motion time, delay event, motion form

  • @Component({
      animations: [
        // 创建动画, 动画名称为 slide
        trigger("slide", [
          // 指定入场动画 注意: 字符串两边不能有空格, 箭头两边可以有也可以没有空格
          // void => * 可以替换为 :enter
          transition("void => *", [
            // 指定元素未入场前的样式
            style({ opacity: 0, transform: "translateY(40px)" }),
            // 指定元素入场后的样式及运动参数
            animate(250, style({ opacity: 1, transform: "translateY(0)" }))
          ]),
          // 指定出场动画
          // * => void 可以替换为 :leave
          transition("* => void", [
            // 指定元素出场后的样式和运动参数
            animate(600, style({ opacity: 0, transform: "translateX(100%)" }))
          ])
        ])
      ]
    })
    Copy after login
    <li @slide></li>
    Copy after login
Note: The default state of the element does not need to be specified in the entrance animation,

Angular will clear the void state as the default state

trigger("slide", [
  transition(":enter", [
    style({ opacity: 0, transform: "translateY(40px)" }),
    animate(250)
  ]),
  transition(":leave", [
    animate(600, style({ opacity: 0, transform: "translateX(100%)" }))
  ])
])
Copy after login
Note: To set the motion parameters of the animation, you need to

animate One parameter of the method is changed to the string type

// 动画执行总时间 延迟时间(可选) 运动形式(可选)
animate("600ms 1s ease-out", style({ opacity: 0, transform: "translateX(100%)" }))
Copy after login
3. Keyframe animation

Keyframe animation uses

keyframes Method definition

transition(":leave", [
  animate(
    600,
    keyframes([
      style({ offset: 0.3, transform: "translateX(-80px)" }),
      style({ offset: 1, transform: "translateX(100%)" })
    ])
  )
])
Copy after login

4. Animation callback

Angular provides two callback functions related to animation, respectively when the animation starts executing and after the animation execution is completed

<li @slide (@slide.start)="start($event)" (@slide.done)="done($event)"></li>
Copy after login
import { AnimationEvent } from "@angular/animations"

start(event: AnimationEvent) {
  console.log(event)
}
done(event: AnimationEvent) {
  console.log(event)
}
Copy after login

5. Create Reusable animation

Place the definition of animation in a separate file to facilitate multiple component calls.

import { animate, keyframes, style, transition, trigger } from "@angular/animations"

export const slide = trigger("slide", [
  transition(":enter", [
    style({ opacity: 0, transform: "translateY(40px)" }),
    animate(250)
  ]),
  transition(":leave", [
    animate(
      600,
      keyframes([
        style({ offset: 0.3, transform: "translateX(-80px)" }),
        style({ offset: 1, transform: "translateX(100%)" })
      ])
    )
  ])
])
Copy after login
import { slide } from "./animations"

@Component({
  animations: [slide]
})
Copy after login

Extract specific animation definitions to facilitate multiple animation calls.

import {animate, animation, keyframes, style, transition, trigger, useAnimation} from "@angular/animations"

export const slideInUp = animation([
  style({ opacity: 0, transform: "translateY(40px)" }),
  animate(250)
])

export const slideOutLeft = animation([
  animate(
    600,
    keyframes([
      style({ offset: 0.3, transform: "translateX(-80px)" }),
      style({ offset: 1, transform: "translateX(100%)" })
    ])
  )
])

export const slide = trigger("slide", [
  transition(":enter", useAnimation(slideInUp)),
  transition(":leave", useAnimation(slideOutLeft))
])
Copy after login

Transfer the total motion time, delay time, and motion form when calling animation

export const slideInUp = animation(
  [
    style({ opacity: 0, transform: "translateY(40px)" }),
    animate("{{ duration }} {{ delay }} {{ easing }}")
  ],
  {
    params: {
      duration: "400ms",
      delay: "0s",
      easing: "ease-out"
    }
  }
)
Copy after login
transition(":enter", useAnimation(slideInUp, {params: {delay: "1s"}}))
Copy after login

6. Query element execution animation

Angular Provided in query Method to find elements and create animations for elements

import { slide } from "./animations"

animations: [
  slide,
  trigger("todoAnimations", [
    transition(":enter", [
      query("h2", [
        style({ transform: "translateY(-30px)" }),
        animate(300)
      ]),
      // 查询子级动画 使其执行
      query("@slide", animateChild())
    ])
  ])
]
Copy after login
<div class="container" @todoAnimations>
  <h2>Todos</h2>
  <ul class="list-group">
    <li
      @slide
      (click)="removeItem(i)"
      *ngFor="let item of todos; let i = index"
      class="list-group-item"
    >
      {{ item }}
    </li>
  </ul>
</div>
Copy after login

By default, parent animation and child animation are executed in order. The parent animation is executed first, and then the child animation is executed. You can use

group Method to make it parallel

trigger("todoAnimations", [
  transition(":enter", [
    group([
      query("h2", [
        style({ transform: "translateY(-30px)" }),
        animate(300)
      ]),
      query("@slide", animateChild())
    ])
  ])
])
Copy after login

7. Staggered animation

Angular provides the stagger method to animate multiple elements at the same time When executing the same animation, delay the execution of each element's animation in turn.

transition(":enter", [
  group([
    query("h2", [
      style({ transform: "translateY(-30px)" }),
      animate(300)
    ]),
    query("@slide", stagger(200, animateChild()))
  ])
])
Copy after login

Note: The

stagger method can only be used inside the query method

8. Custom status animation

Angular provides the state method for defining state.

An in-depth analysis of how to use animation in Angular

Default code analysis

<div class="container">
  <div class="panel panel-default">
    <div class="panel-heading" (click)="toggle()">
      一套框架, 多种平台, 移动端 & 桌面端
    </div>
    <div class="panel-body">
      <p>
        使用简单的声明式模板,快速实现各种特性。使用自定义组件和大量现有组件,扩展模板语言。在几乎所有的
        IDE 中获得针对 Angular
        的即时帮助和反馈。所有这一切,都是为了帮助你编写漂亮的应用,而不是绞尽脑汁的让代码“能用”。
      </p>
      <p>
        从原型到全球部署,Angular 都能带给你支撑 Google
        大型应用的那些高延展性基础设施与技术。
      </p>
      <p>
        通过 Web Worker 和服务端渲染,达到在如今(以及未来)的 Web
        平台上所能达到的最高速度。 Angular 让你有效掌控可伸缩性。基于
        RxJS、Immutable.js 和其它推送模型,能适应海量数据需求。
      </p>
      <p>
        学会用 Angular
        构建应用,然后把这些代码和能力复用在多种多种不同平台的应用上 ——
        Web、移动 Web、移动应用、原生应用和桌面原生应用。
      </p>
    </div>
  </div>
</div>
<style>
  .container {
    margin-top: 100px;
  }
  .panel-heading {
    cursor: pointer;
  }
</style>
Copy after login
import { Component } from "@angular/core"

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styles: []
})
export class AppComponent {
  isExpended: boolean = false
  toggle() {
    this.isExpended = !this.isExpended
  }
}
Copy after login

Create animation

trigger("expandCollapse", [
  // 使用 state 方法定义折叠状态元素对应的样式
  state(
    "collapsed",
    style({
      height: 0,
      overflow: "hidden",
      paddingTop: 0,
      paddingBottom: 0
    })
  ),
  // 使用 state 方法定义展开状态元素对应的样式
  state("expanded", style({ height: "*", overflow: "auto" })),
  // 定义展开动画
  transition("collapsed => expanded", animate("400ms ease-out")),
  // 定义折叠动画
  transition("expanded => collapsed", animate("400ms ease-in"))
])
Copy after login
<div class="panel-body" [@expandCollapse]="isExpended ? &#39;expanded&#39; : &#39;collapsed&#39;"></div>
Copy after login

9. 路由动画

An in-depth analysis of how to use animation in Angular

为路由添加状态标识,此标识即为路由执行动画时的自定义状态

const routes: Routes = [
  {
    path: "",
    component: HomeComponent,
    pathMatch: "full",
    data: {
      animation: "one" 
    }
  },
  {
    path: "about",
    component: AboutComponent,
    data: {
      animation: "two"
    }
  },
  {
    path: "news",
    component: NewsComponent,
    data: {
      animation: "three"
    }
  }
]
Copy after login

通过路由插座对象获取路由状态标识,并将标识传递给动画的调用者,让动画执行当前要执行的状态是什么

<div class="routerContainer" [@routerAnimations]="prepareRoute(outlet)">
  <router-outlet #outlet="outlet"></router-outlet>
</div>
Copy after login
import { RouterOutlet } from "@angular/router"

export class AppComponent {
  prepareRoute(outlet: RouterOutlet) {
    return (
      outlet &&
      outlet.activatedRouteData &&
      outlet.activatedRouteData.animation
    )
  }
}
Copy after login

routerContainer 设置为相对定位,将它的直接一级子元素设置成绝对定位

/* styles.css */
.routerContainer {
  position: relative;
}

.routerContainer > * {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
}
Copy after login

创建动画

trigger("routerAnimations", [
  transition("one => two, one => three, two => three", [
    query(":enter", style({ transform: "translateX(100%)", opacity: 0 })),
    group([
      query(
        ":enter",
        animate(
          "0.4s ease-in",
          style({ transform: "translateX(0)", opacity: 1 })
        )
      ),
      query(
        ":leave",
        animate(
          "0.4s ease-out",
          style({
            transform: "translateX(-100%)",
            opacity: 0
          })
        )
      )
    ])
  ]),
  transition("three => two, three => one, two => one", [
    query(
      ":enter",
      style({ transform: "translateX(-100%)", opacity: 0 })
    ),
    group([
      query(
        ":enter",
        animate(
          "0.4s ease-in",
          style({ transform: "translateX(0)", opacity: 1 })
        )
      ),
      query(
        ":leave",
        animate(
          "0.4s ease-out",
          style({
            transform: "translateX(100%)",
            opacity: 0
          })
        )
      )
    ])
  ])
])
Copy after login

更多编程相关知识,请访问:编程视频!!

The above is the detailed content of An in-depth analysis of how to use animation in Angular. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:juejin.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template