返回

巧用 Angular animations 动效,提升前端开发效率

前端

在 Angular 应用中,动画动效扮演着至关重要的角色,它不仅能够提升用户体验,让交互更加直观和生动,还能让应用看起来更加现代和专业。Angular animations 提供了一套强大的工具和功能,帮助开发者轻松创建各种动画效果,让应用焕发活力。

1. 开场即有的动画

1.1 定义一个动画函数

import { trigger, state, style, transition, animate } from '@angular/animations';

export const fadeIn = trigger('fadeIn', [
  state('void', style({ opacity: 0 })),
  transition(':enter', [
    animate('300ms ease-in', style({ opacity: 1 }))
  ])
]);

1.2 在要用的地方的ts里

import { Component, OnInit } from '@angular/core';
import { trigger, state, style, transition, animate } from '@angular/animations';

@Component({
  selector: 'app-fade-in',
  templateUrl: './fade-in.component.html',
  styleUrls: ['./fade-in.component.css'],
  animations: [
    trigger('fadeIn', [
      state('void', style({ opacity: 0 })),
      transition(':enter', [
        animate('300ms ease-in', style({ opacity: 1 }))
      ])
    ])
  ]
})
export class FadeInComponent implements OnInit {

  constructor() { }

  ngOnInit(): void {
  }

}

1.3 html里

<div [@fadeIn]>...</div>

2. 主动触发动画

2.1 定义动画触发器

import { Component, OnInit } from '@angular/core';
import { trigger, state, style, transition, animate } from '@angular/animations';

@Component({
  selector: 'app-fade-in-out',
  templateUrl: './fade-in-out.component.html',
  styleUrls: ['./fade-in-out.component.css'],
  animations: [
    trigger('fadeInOut', [
      state('void', style({ opacity: 0 })),
      transition(':enter', [
        animate('300ms ease-in', style({ opacity: 1 }))
      ]),
      transition(':leave', [
        animate('300ms ease-out', style({ opacity: 0 }))
      ])
    ])
  ]
})
export class FadeInOutComponent implements OnInit {

  isShow = false;

  constructor() { }

  ngOnInit(): void {
  }

  toggleShow() {
    this.isShow = !this.isShow;
  }

}

2.2 html中使用

<div [@fadeInOut]="isShow ? 'enter' : 'leave'"></div>
<button (click)="toggleShow()">Toggle</button>

结语

Angular animations 是一个功能强大的工具,它可以帮助开发者创建各种各样的动画效果,让 Angular 应用更加生动和交互性。在本文中,我们介绍了如何使用 Angular animations 来创建开场动画和主动触发动画。希望这些示例能够帮助您更好地理解 Angular animations 的用法,并将其应用到您的 Angular 项目中。