面试题答案
一键面试- 引入模块:
- 在
app.module.ts
中引入BrowserAnimationsModule
(如果使用的是浏览器平台)。
import { BrowserAnimationsModule } from '@angular/platform - browser/animations'; @NgModule({ imports: [ // 其他模块 BrowserAnimationsModule ], // 其他模块配置 }) export class AppModule {}
- 在
- 组件修改:
- 不需要在组件类中有特别针对动画逻辑的变量声明,除非需要控制动画的一些额外状态(例如动画时长等,这里暂不考虑)。
- 模板修改:
- 使用
@keyframes
定义淡入淡出的关键帧动画。 - 使用
[@动画名称]
语法在ngFor
循环的元素上应用动画。
<div *ngFor="let task of tasks; let i = index" [@fadeAnimation]> {{task}} <button (click)="deleteTask(i)">Delete</button> </div> <input [(ngModel)]="newTask" placeholder="Enter new task"> <button (click)="addTask()">Add Task</button>
- 在组件的
@Component
装饰器中定义动画:
上述代码中,import { Component, OnInit } from '@angular/core'; import { trigger, state, style, transition, animate } from '@angular/animations'; @Component({ selector: 'app - task - list', templateUrl: './task - list.component.html', styleUrls: ['./task - list.component.css'], animations: [ trigger('fadeAnimation', [ transition(':enter', [ style({ opacity: 0 }), animate('300ms', style({ opacity: 1 })) ]), transition(':leave', [ animate('300ms', style({ opacity: 0 })) ]) ]) ] }) export class TaskListComponent implements OnInit { tasks: string[] = []; newTask: string = ''; ngOnInit() {} addTask() { this.tasks.push(this.newTask); this.newTask = ''; } deleteTask(index: number) { this.tasks.splice(index, 1); } }
@keyframes
定义了fadeAnimation
动画,:enter
状态表示元素进入时的动画,从透明度0淡入到透明度1,:leave
状态表示元素离开时的动画,从透明度1淡出到透明度0。在ngFor
循环的div
元素上应用了这个动画,当添加或删除任务时,对应的元素会有淡入淡出的动画效果。addTask
和deleteTask
方法分别处理任务的添加和删除逻辑。 - 使用