You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 18中Animations Module启用方法咨询

Angular 18 启用动画模块实现div移动效果

1. 先搞定依赖(必要步骤)

Angular 18的动画模块是独立包,先确保安装到位:

npm install @angular/animations

2. 启用动画模块(分两种项目类型)

独立组件项目(Angular 18默认推荐)

直接在你的根组件(比如app.component.ts)的providers数组里加入provideAnimations(),同时导入动画相关API:

// app.component.ts
import { Component, provideAnimations } from '@angular/core';
import { animate, state, style, transition, trigger } from '@angular/animations';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [],
  providers: [provideAnimations()], // 这一步就是启用动画
  templateUrl: './app.component.html',
  styleUrl: './app.component.css',
  animations: [
    // 定义动画触发器:控制div从左到右移动
    trigger('moveDiv', [
      state('start', style({ left: '0px' })),
      state('end', style({ left: '300px' })),
      transition('start <=> end', animate('500ms ease-in-out'))
    ])
  ]
})
export class AppComponent {
  divState = 'start';

  toggleMove() {
    this.divState = this.divState === 'start' ? 'end' : 'start';
  }
}

传统NgModule项目

如果你的项目还是用NgModule结构,就在根模块app.module.ts的imports里导入BrowserAnimationsModule:

// 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({
  declarations: [AppComponent],
  imports: [BrowserModule, BrowserAnimationsModule], // 启用全局动画
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

3. 写模板和样式

在app.component.html里加按钮和带动画的div:

<button (click)="toggleMove()">点击移动div</button>
<div [@moveDiv]="divState" class="moving-div"></div>

在app.component.css里设置div的基础样式:

.moving-div {
  position: absolute;
  width: 100px;
  height: 100px;
  background-color: #42b983;
  top: 100px;
}

关键文件说明

  • app.component.ts:核心逻辑载体,负责导入动画API、定义动画规则、控制状态切换
  • app.component.html:绑定动画触发器和点击事件,把逻辑和视图连起来
  • app.component.css:给div设置基础定位,让动画能生效
  • 若用NgModule,app.module.ts:导入动画模块开启全局支持

内容的提问来源于stack exchange,提问作者Eric Bishop

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 11:42:03