Usare le animazioni in Angular
Angular dispone già di un modulo per creare delle animazioni.
Non c'è da installare nulla, va solo attivato: BrowserAnimationsModule.
Per farlo dovete aggiungerlo in app.module.ts:
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {
}
Fatto questo, dentro al nostro component facciamo una cosa del genere:
import {Component, OnInit} from '@angular/core';
import {
trigger,
state,
style,
animate,
transition,
} from '@angular/animations';
@Component({
selector: 'app-root',
animations: [
trigger('openClose', [
state('aperto', style({
height: '200px',
opacity: 1,
backgroundColor: 'green'
})),
state('chiuso', style({
height: '100px',
opacity: 0.8,
backgroundColor: 'red'
})),
transition('aperto => chiuso', [
animate('1s')
]),
transition('chiuso => aperto', [
animate('0.5s')
]),
]),
],
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
checkAperto = false;
lbl = 'Chiuso';
toggle() {
this.checkAperto = !this.checkAperto;
if (!this.checkAperto) {
this.lbl = 'Chiuso';
} else {
this.lbl = 'Aperto';
}
}
constructor() {
}
ngOnInit(): void {
}
}
Con trigger indichiamo che azione dobbiamo richiamare.
Con state indichiamo lo stile da applicare ai vari stati.
Con transition indichiamo l'animazione al cambio di stato.
Questo l'HTML:
<button type="button" (click)="toggle()">Clicca</button>
<br><br>
<div [@openClose]="checkAperto ? 'aperto' : 'chiuso'" class="open-close-container">
<p>Quest è il box: {{lbl}}</p>
</div>
Enjoy!
typescript angular animiations browseranimationsmodule
Commentami!