Angular 17+ 高级教程 – Animation 动画

前言

Angular 有一套 built-in 的 Animation 方案。这套方案的底层实现是基于游览器原生的 Web Animation API。

CSS Transition -> CSS Animation -> Web Animation API -> Angular Animation 这 4 套方案的关系并不是互相替代,而是互相弥补。

越靠后的方案就越复杂,所以对于使用者来说,如果不是真的有必要,应该要尽可能使用靠前面的方案。

本篇会假设你对 CSS Transition、CSS Animation、Web Animation API 已经熟悉,会在这些基础之上讲解 Angular Animation。

不熟悉它们的朋友可以先看下面这两篇文章。

  1. CSS – Transition & Animation
  2. DOM – Web Animation API

Angular Animation 虽然是对原生 Web Animation API 的封装和扩展,但 Angular 并没有完全公开所有 Web Animation API 的接口,

也就是说,我们不一定可以使用 Angular Animation 做出 Web Animation API 的效果,或者说使用 Angular Animation 可能会更难达到效果。

所以在面对不同动画需求时,我们一定要慎选方案。

本篇将从 Angular Animation 比较底层的使用方式开始,大致对比 Angular Animation 和 Web Animation API 的区别,看看它们的共同点和不同之处。

然后在深入 Angular Animation 独有的功能和日常使用方式,最后微微逛一下源码,开始吧 🚀。

 

AnimationBuilder

AnimationBuilder 是一个 Root Level Dependancy Injection Provider。

它比较底层,日常开发中很少会用到,但是从它开始理解 Angular Animation 会比较轻松,所以我们从它开始。

搭环境

我们搭个测试环境,对比 Angular Animation 和 Web Animation API。

App Template

<div class="box-list"  >
  <div #nativeBox class="box"></div>
  <div #ngBox class="box"></div>
</div>

两个 div box 做 compare。

第一个是 native box,将使用 Web Animation API,

第二个是 ng box,将使用 Angular Animation。

App Styles

:host {
  display: block;
  padding: 56px;
}

.box-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.box {
  width: 100px;
  height: 100px;
  background-color: red;
}

效果

The Simplest Aniamtion

我们为 2 个 box 添加一个简单的 animation。

native box 使用 Web Animation API,ng box 使用 Angular Animation。

App 组件

export class AppComponent {
  // 1. query both boxes
  readonly nativeBox = viewChild.required<string, ElementRef<HTMLElement>>('nativeBox', { read: ElementRef });
  readonly ngBox = viewChild.required<string, ElementRef<HTMLElement>>('ngBox', { read: ElementRef });

  constructor() {
    // 2. inject AnimationBuilder
    const builder = inject(AnimationBuilder);

    afterNextRender(() => {
      // 3. delay 1 second (只是为了比较容易看效果)
      window.setTimeout(() => {
        // 4. get box HTMLElement
        const nativeBox = this.nativeBox().nativeElement;
        const ngBox = this.ngBox().nativeElement;

        // 5. use Web Aniamtion API for native box
        const nativePlayer = nativeBox.animate([{ width: '200px' }], {
          duration: 1000,
          fill: 'forwards',
          easing: 'ease',
        });

        // 6. use Angular Animation for ng box
        const factory = builder.build([animate('1s ease', style({ width: '200px' }))]);
        const ngPlayer = factory.create(ngBox);
        ngPlayer.play();
      }, 1000);
    });
  }
}

效果

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

目录

上一篇 Angular 17+ 高级教程 – HttpClient

下一篇 Angular 17+ 高级教程 – Reactive Forms

想查看目录,请移步 Angular 17+ 高级教程 – 目录

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章