运行代码创建component
ng g c animate-test
然后在app.module.ts做如下引入
分别是下面两行,自行引入
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';//注意这个很重要 BrowserAnimationsModule,//注意这个很关键,没有引入动不起来
接下来傻瓜式拷贝代码
animate-test.component.html
<button (click)="toggle()">{{yellowOrGreen ? '你黄了!':'你被绿了!'}}</button> <div [@openClose]="yellowOrGreen ? 'yellow' : 'green'" > <p>{{yellowOrGreen ? '你黄了!':'你被绿了!'}}</p> </div>
animate-test.component.ts
import {Component, OnInit} from '@angular/core'; import {trigger, state, style, animate, transition} from '@angular/animations'; @Component({ selector: 'app-animate-test', templateUrl: './animate-test.component.html', styleUrls: ['./animate-test.component.css'], animations: [ trigger('openClose', [ state('yellow', style({height: '50px', color: 'black', backgroundColor: 'yellow'})), state('green', style({height: '100px', color: 'white', fontSize: '40px', fontWeight: 'bold', backgroundColor: 'green'}) ), transition('yellow=>green', [animate('0.3s')]), transition('green=>yellow', [animate('0.5s')]), // transition('yellow <=> green', [animate('1s')]) //双箭头可以指定两个状态互相转场 ]) ] }) export class AnimateTestComponent implements OnInit { public yellowOrGreen = true; ngOnInit() { } public toggle() { this.yellowOrGreen = !this.yellowOrGreen; } }
然后别忘了在app-routing.module.ts路由里面加入这个组件页面哟~
import {AnimateTestComponent} from "./components/animate-test/animate-test.component"; { path: 'animate-test', component: AnimateTestComponent,//同步加载 },
然后ng start --open跑起来吧亲~
注意访问地址大概是http://localhost:4200/animate-test
点击按钮之后就