Angular9 animations
1、 需要引入BrowserAnimationsModule
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { SlideImgComponent } from './slide-img/slide-img.component';
@NgModule({
declarations: [
AppComponent,
SlideImgComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
2 、需要引入trigger, state, animate, transition, style
import { trigger, state, animate, transition, style } from ‘@angular/animations’;
3、制作一个简单的左右移动的动画
.component.html文件:
<div [@carousel]='state' (click)='changeState()'>👈左右👉</div>
.component.ts文件:
import { Component, OnInit } from '@angular/core';
import { trigger, state, animate, transition, style } from '@angular/animations';
@Component({
selector: 'app-slide-img',
templateUrl: './slide-img.component.html',
styleUrls: ['./slide-img.component.css'] ,
animations: [
trigger('carousel', [
state('left', style({
marginLeft: '0px',
})),
state('right', style({
marginLeft: '100px',
})),
transition('left => right', animate('500ms ease-in-out', style({
marginLeft: '100px'
}))),
transition('right => left', animate('500ms ease-in-out', style({
})))
])
]
})
export class SlideImgComponent implements OnInit {
state = 'left';
constructor() { }
ngOnInit(): void {
}
changeState(){
this.state = this.state === 'left' ? 'right' : 'left';
}
}
一个奇怪的问题:从left到right的时候,如果不在style中加上marginLeft: ‘100px’,那么这个过度效果是不能生效的。分析的原因大概是从左到右的时候marginLeft的100的值,并没有获取到,动画只要起点的值没有终点的值,所有动画运行不了。当回来的时候,起点和终点的值都有了。但是当再次从左到右的时候还是不行,难道这个值又给清空了?
4、制作一个图片轮播
好,道理我们都懂了,那么我们能来制作一个图片轮播吧。
……
参考文档:https://angular.cn/guide/animations