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+ 高級教程 – 目錄

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