Существует несколько способов анимации текста при его изменении. Но я предпочитаю использовать 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 анимациях можно найти здесь .