要实现Angular动画只触发一次,可以使用oneTime
选项。以下是一个包含代码示例的解决方法:
首先,在你的组件中引入动画模块:
import { trigger, transition, animate, style } from '@angular/animations';
然后,在@Component
装饰器中定义动画:
@Component({
selector: 'app-your-component',
templateUrl: './your-component.component.html',
styleUrls: ['./your-component.component.css'],
animations: [
trigger('fadeInOut', [
transition(':enter', [
style({ opacity: 0 }),
animate('500ms', style({ opacity: 1 }))
], { oneTime: true }),
transition(':leave', [
animate('500ms', style({ opacity: 0 }))
])
])
]
})
在模板文件中使用动画:
Hello World!
这样,当组件首次渲染时,动画将触发一次,并且不会再次触发。
注意:需要确保已在app.module.ts
中导入BrowserAnimationsModule
模块,以启用动画支持:
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
@NgModule({
imports: [
BrowserModule,
BrowserAnimationsModule
],
// ...
})
export class AppModule { }