An in-depth analysis of how to use animation in Angular
This article will introduce you to Angular animation, I hope it will be helpful to you! !
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"]
1.2 Types of status
In Angular
, there are three types of status, namely: void
, *
, custom
1.3 Entry and exit animationEntry 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: This state occurs when an element has been created in memory but has not yet been added to DOM
*: The state after the element is inserted into theor removed from
DOM
DOM
tree, or the state of the element already in the
DOMtree, 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.
void => * means, the alias is
:enter
* => void, the alias is
:leave
BrowserAnimationsModule
import { BrowserAnimationsModule } from "@angular/platform-browser/animations" @NgModule({ imports: [BrowserAnimationsModule], }) export class AppModule {}
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) } }
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%)" })) ]) ]) ] })
<li @slide></li>
Note: The default state of the element does not need to be specified in the entrance animation,Angular
will clear the
voidstate 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 to3. Keyframe animationKeyframe animation usesanimate
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
keyframes Method definition
transition(":leave", [ animate( 600, keyframes([ style({ offset: 0.3, transform: "translateX(-80px)" }), style({ offset: 1, transform: "translateX(100%)" }) ]) ) ])
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) }
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] })
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)) ])
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"}}))
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()) ]) ]) ]
<div class="container" @todoAnimations> <h2 id="Todos">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>
group Method to make it parallel
trigger("todoAnimations", [ transition(":enter", [ group([ query("h2", [ style({ transform: "translateY(-30px)" }), animate(300) ]), query("@slide", animateChild()) ]) ]) ])
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())) ]) ])
Note: The8. Custom status animationstagger
method can only be used inside the
querymethod
Angular provides the
state method for defining state.
<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 } }
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 ? 'expanded' : 'collapsed'"></div>
9. 路由动画
为路由添加状态标识,此标识即为路由执行动画时的自定义状态
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" } } ]
通过路由插座对象获取路由状态标识,并将标识传递给动画的调用者,让动画执行当前要执行的状态是什么
<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 ) } }
将 routerContainer
设置为相对定位,将它的直接一级子元素设置成绝对定位
/* styles.css */ .routerContainer { position: relative; } .routerContainer > * { position: absolute; left: 0; top: 0; width: 100%; }
创建动画
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 An in-depth analysis of how to use animation in Angular. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











When Microsoft launched Windows 11, it brought a lot of changes. One of the changes is an increase in the number of user interface animations. Some users want to change the way things appear, and they have to find a way to do it. Having animations makes it feel better and more user-friendly. Animation uses visual effects to make the computer look more attractive and responsive. Some of them include sliding menus after a few seconds or minutes. There are many animations on your computer that can affect PC performance, slow it down, and interfere with your work. In this case you have to turn off animation. This article will introduce several ways that users can improve the speed of their animations on PC. You can apply the changes using Registry Editor or a custom file you run. How to improve animations in Windows 11
![Animation not working in PowerPoint [Fixed]](https://img.php.cn/upload/article/000/887/227/170831232982910.jpg?x-oss-process=image/resize,m_fill,h_207,w_330)
Are you trying to create a presentation but can't add animation? If animations are not working in PowerPoint on your Windows PC, then this article will help you. This is a common problem that many people complain about. For example, animations may stop working during presentations in Microsoft Teams or during screen recordings. In this guide, we will explore various troubleshooting techniques to help you fix animations not working in PowerPoint on Windows. Why aren't my PowerPoint animations working? We have noticed that some possible reasons that may cause the animation in PowerPoint not working issue on Windows are as follows: Due to personal

CSS animation: How to achieve the flash effect of elements, specific code examples are needed. In web design, animation effects can sometimes bring a good user experience to the page. The glitter effect is a common animation effect that can make elements more eye-catching. The following will introduce how to use CSS to achieve the flash effect of elements. 1. Basic implementation of flash First, we need to use the animation property of CSS to achieve the flash effect. The value of the animation attribute needs to specify the animation name, animation execution time, and animation delay time

Angular.js is a freely accessible JavaScript platform for creating dynamic applications. It allows you to express various aspects of your application quickly and clearly by extending the syntax of HTML as a template language. Angular.js provides a range of tools to help you write, update and test your code. Additionally, it provides many features such as routing and form management. This guide will discuss how to install Angular on Ubuntu24. First, you need to install Node.js. Node.js is a JavaScript running environment based on the ChromeV8 engine that allows you to run JavaScript code on the server side. To be in Ub

With the rapid development of the Internet, front-end development technology is also constantly improving and iterating. PHP and Angular are two technologies widely used in front-end development. PHP is a server-side scripting language that can handle tasks such as processing forms, generating dynamic pages, and managing access permissions. Angular is a JavaScript framework that can be used to develop single-page applications and build componentized web applications. This article will introduce how to use PHP and Angular for front-end development, and how to combine them

This website reported on January 26 that the domestic 3D animated film "Er Lang Shen: The Deep Sea Dragon" released a set of latest stills and officially announced that it will be released on July 13. It is understood that "Er Lang Shen: The Deep Sea Dragon" is produced by Mihuxing (Beijing) Animation Co., Ltd., Horgos Zhonghe Qiancheng Film Co., Ltd., Zhejiang Hengdian Film Co., Ltd., Zhejiang Gongying Film Co., Ltd., Chengdu The animated film produced by Tianhuo Technology Co., Ltd. and Huawen Image (Beijing) Film Co., Ltd. and directed by Wang Jun was originally scheduled to be released in mainland China on July 22, 2022. Synopsis of the plot of this site: After the Battle of the Conferred Gods, Jiang Ziya took the "Conferred Gods List" to divide the gods, and then the Conferred Gods List was sealed by the Heavenly Court under the deep sea of Kyushu Secret Realm. In fact, in addition to conferring divine positions, there are also many powerful evil spirits sealed in the Conferred Gods List.

How to use Vue to implement typewriter animation special effects Typewriter animation is a common and eye-catching special effect that is often used in website titles, slogans and other text displays. In Vue, we can achieve typewriter animation effects by using Vue custom instructions. This article will introduce in detail how to use Vue to achieve this special effect and provide specific code examples. Step 1: Create a Vue project First, we need to create a Vue project. You can use VueCLI to quickly create a new Vue project, or manually

The content that needs to be rewritten on this site is: 9 The content that needs to be rewritten is: Month The content that needs to be rewritten is: 23 The content that needs to be rewritten is: Daily News, the main line drama of the second season of the animated series "Arknights" "Arknights: Winter Hidden Return" has announced its final release. The content that needs to be rewritten is: PV. The content that needs to be rewritten is: 10. The content that needs to be rewritten is: 7. The content that needs to be rewritten is: 7 The content is: The content that needs to be rewritten is: 00:23 The content that needs to be rewritten is: Officially launched, click here to enter the official website of the theme. The content that needs to be re-written is: This site has noticed that "Arknights: Winter Hidden Return" is the sequel to "Arknights: Prelude to Dawn". The plot summary is as follows: In order to prevent the infected, a group of
