search
HomeWeb Front-endJS TutorialAngular learning: in-depth chat about status and animation

This article will give you an in-depth understanding of the status and animation in Angular, briefly introduce the method of creating animation, and talk about key frame animation, animation callback, reusable animation, interleaved animation and other knowledge points. I hope it will be useful to everyone. Helped!

Angular learning: in-depth chat about status and animation

State


1. What is state

State represents the style of the element to be moved at different stages of movement.

Angular learning: in-depth chat about status and animation

2. Types of states

In Angular, there are three types of states, namely : void, *, custom
Angular learning: in-depth chat about status and animation
void: When the element is created in memory but has not yet This state occurs when an element is added to or deleted from the DOM [Related tutorial recommendation: "angular tutorial"]

*: The element is inserted The state after reaching 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, from Movement from one state to another, such as the folding and unfolding of a panel.

3. Entry and exit animation

Entry animation refers to the element that appears in front of the user in the form of animation after it is created. Entry animation The status is represented by void => *, and the alias is :enter

Angular learning: in-depth chat about status and animation##. The exit animation refers to a period of execution before the element is deleted. Say goodbye to animation, use
* => void for the status of exit animation, and the alias is :leave

Angular learning: in-depth chat about status and animation

## to get started quickly

1. Before using 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 {}

2. 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" />
<div class="container">
  <h2 id="Todos">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>
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)
  }
}

3. Create animation

    trigger method is used to create animation, specify the animation name
  • ## The #transition method is used to specify the motion state of the animation, exit animation or entry animation, or custom state animation.
  • The style method is used to set the style corresponding to the element in different states.
  • The 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%)" }))
          ])
        ])
      ]
    })

    Note: The entry animation does not need to specify the default state of the element, 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%)" }))
      ])
    ])
Note: To set the motion parameters of the animation, you need to change one parameter of the animate method to a string type

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

Keyframe animation

Keyframe animation usage

keyframes
Method definition

<pre class='brush:php;toolbar:false;'>transition(&quot;:leave&quot;, [ animate( 600, keyframes([ style({ offset: 0.3, transform: &quot;translateX(-80px)&quot; }), style({ offset: 1, transform: &quot;translateX(100%)&quot; }) ]) ) ])</pre>
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>
import { AnimationEvent } from "@angular/animations"

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

Create reusable animation

1. Place the definition of the animation in a separate file, which is more convenient Component call.


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%)" })
      ])
    )
  ])
])
import { slide } from "./animations"

@Component({
  animations: [slide]
})

2. 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))
])

3. When calling animation, transfer the total time of movement, delay time, and movement form

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

Query element execution animation

Angular Provides

query
method to find elements and create animations for elements

<pre class='brush:php;toolbar:false;'>import { slide } from &quot;./animations&quot; animations: [ slide, trigger(&quot;todoAnimations&quot;, [ transition(&quot;:enter&quot;, [ query(&quot;h2&quot;, [ style({ transform: &quot;translateY(-30px)&quot; }), animate(300) ]), // 查询子级动画 使其执行 query(&quot;@slide&quot;, animateChild()) ]) ]) ]</pre><pre class='brush:php;toolbar:false;'>&lt;div class=&quot;container&quot; @todoAnimations&gt; &lt;h2 id=&quot;Todos&quot;&gt;Todos&lt;/h2&gt; &lt;ul class=&quot;list-group&quot;&gt; &lt;li @slide (click)=&quot;removeItem(i)&quot; *ngFor=&quot;let item of todos; let i = index&quot; class=&quot;list-group-item&quot; &gt; {{ item }} &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt;</pre>By default, parent animation and child animation are executed in order, the parent animation is executed first, and then the child animation is executed. Level animation, you can use the
group

method to make it parallel

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

Angular provides the stagger method to run multiple elements When executing the same animation at the same time, 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()))
  ])
])

Note: The stagger method can only be used inside the query method

Custom state animation

Angular provides

state
method is used to define state.


1. Default code analysisAngular learning: in-depth chat about status and animation

<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>
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
  }
}

2. 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"))
])
<div class="panel-body" [@expandCollapse]="isExpended ? &#39;expanded&#39; : &#39;collapsed&#39;"></div>

Routing animation


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

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"
    }
  }
]

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

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

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

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

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

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

4、创建动画

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
          })
        )
      )
    ])
  ])
])

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

The above is the detailed content of Angular learning: in-depth chat about status and animation. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool