首页 > 解决方案 > 如何为 angular8 中不是列表的变量的变化设置动画?

问题描述

我有以下变量:

“测试”,默认为“某些文本”

在我的模板中,我使用它:{{test}}

如何使每当用户单击更改“测试”变量内容(例如“另一个不同的文本”)的按钮时,文本本身或父 div 上会出现淡出和淡入动画?我看到的大多数例子都涉及列表......有没有办法做到这一点?

标签: cssangular

解决方案


当文本发生变化时,有多种方法可以为文本设置动画。但我更喜欢使用 Angular 动画,因为它提供了一些漂亮的辅助函数和动画事件回调。

下面的代码片段使用 Angular 动画对文本的更改进行动画处理。代码片段中添加了注释以解释发生了什么。

html模板文件:

<h1>Angular Animations Example</h1>
<div>
    <label>Name is: </label>
    <span class="text"
      [@animateText]="currentState"
      (@animateText.done)="animationFinished($event)"
    >
      {{ text }}
    </span>
</div>
<br/>
<button (click)="changeText()">Change Text</button>

组件文件:

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ],
  animations: [
    // Define the custom animation trigger
    trigger('animateText', [
      // Defining the hidden state
      state('hidden', style({
        opacity: 0
      })),
      // Defining the visible state
      state('visible', style({
        opacity: 1
      })),
      // Defining the animation for state changes
      transition('hidden <=> visible', [
        animate('1s ease')
      ])
    ])
  ]
})
export class AppComponent  {
  text = 'Angular';

  // Start with hidden state and then change it to visible state 
  // to animate the text when the component is rendered
  currentState = 'hidden';

  changeText() {
    // Do not change the text
    // instead change the state to hidden first for fade away animation

    this.currentState = 'hidden';
  }

  // This method is called when the animation has finished playing
  animationFinished(event: AnimationEvent) {
    if (event.fromState === 'void' && event.toState === 'hidden') {
      /** 
       * This block executes when the component is rendered initially.
       * Change the state to visible once the component has been initialized
       * to play the animation
       */

      this.currentState = 'visible';
    } else if (event.fromState === 'visible' && event.toState === 'hidden') {
      /**
       * Once the previous text fades, perform the text change logic
       * and then change state to visible to play the animation
       */

      this.text = this.text === 'Angular' ? 'Stackblitz' : 'Angular';
      this.currentState = 'visible';
    }
  }
}

不要忘记包含BrowserAnimationsModule在 AppModule 文件中。

app.module.ts

import { NgModule } from "@angular/core";
import { BrowserModule } from "@angular/platform-browser";
import { BrowserAnimationsModule } from "@angular/platform-browser/animations";

import { AppComponent } from "./app.component";

@NgModule({
  imports: [BrowserModule, BrowserAnimationsModule],
  declarations: [AppComponent],
  bootstrap: [AppComponent]
})
export class AppModule {}

您可以在此处找到我在 Stackblitz 上创建的示例。更多关于 Angular 动画的信息可以在这里找到。


推荐阅读