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