MST
星途 面试题库

面试题:Angular的ngFor指令中如何处理动态添加或删除列表项时的过渡效果

现有一个Angular应用,使用ngFor指令展示一个任务列表。当用户添加新任务或删除现有任务时,希望实现过渡动画效果,如淡入淡出。请说明实现此功能的步骤,包括需要引入的模块、在组件和模板中要做的修改,同时给出关键代码片段。
11.2万 热度难度
前端开发Angular

知识考点

AI 面试

面试题答案

一键面试
  1. 引入模块
    • app.module.ts中引入BrowserAnimationsModule(如果使用的是浏览器平台)。
    import { BrowserAnimationsModule } from '@angular/platform - browser/animations';
    
    @NgModule({
      imports: [
        // 其他模块
        BrowserAnimationsModule
      ],
      // 其他模块配置
    })
    export class AppModule {}
    
  2. 组件修改
    • 不需要在组件类中有特别针对动画逻辑的变量声明,除非需要控制动画的一些额外状态(例如动画时长等,这里暂不考虑)。
  3. 模板修改
    • 使用@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元素上应用了这个动画,当添加或删除任务时,对应的元素会有淡入淡出的动画效果。addTaskdeleteTask方法分别处理任务的添加和删除逻辑。