css - 如何为 angular8 中不是列表的变量的变化设置动画?
问题描述
我有以下变量:
“测试”,默认为“某些文本”
在我的模板中,我使用它:{{test}}
如何使每当用户单击更改“测试”变量内容(例如“另一个不同的文本”)的按钮时,文本本身或父 div 上会出现淡出和淡入动画?我看到的大多数例子都涉及列表......有没有办法做到这一点?
解决方案
当文本发生变化时,有多种方法可以为文本设置动画。但我更喜欢使用 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 {}
推荐阅读
- javascript - 有没有办法在 JavaScript 中遍历一个可能自包含的对象?
- python - 基于时间范围,如何在python中从应用程序日志中grep整个线程日志
- c# - 从包含视图的测试中运行控制器操作
- javascript - 如何将 JSON 日期转换为日历格式?
- android - 如何在 Wear OS 上获得低带宽网络访问以进行休息通话?
- asp.net - 出现系统错误 67。找不到网络名称
- qt - linux的sync()在哪里定义。关闭应用程序后,不会保留写入 QSettings 的数据
- visual-studio - 最新版本的nuget包仍然不是最新的
- azure-log-analytics - 检查是否存在 Kusto 语言的表?
- nginx - Nginx:如何生成 X-B3-SpanId 16 个随机字节用于跟踪