我正在尝试创建一个在Angular 2中动画结束时触发的函数(我正在使用最新的角度cli)。
我一直在Angular Animations上通过为回调分配回调来了解如何实现这一点 在我的代码示例中,我有一个动画到页面上的组件。代码如下:
//first.component.ts
import { Component, OnInit } from '@angular/core';
import { trigger, state, style, animate, transition } from '@angular/core';
@Component({
selector: 'app-first',
templateUrl: './first.component.html',
styleUrls: ['./first.component.css'],
host: {
'[@routeAnimation]': 'true',
'[style.display]': "'block'",
'[style.position]': "'absolute'"
},
animations: [
trigger('routeAnimation', [
state('*', style({transform: 'translateX(0)', opacity: 1})),
transition('void => *', [style({transform: 'translateX(-100%)', opacity: 0}),animate(500)]),
transition('* => void', animate(500, style({transform: 'translateX(100%)', opacity: 0})))
])
]
})
export class FirstComponent implements OnInit {
constructor() { }
ngOnInit() {
}
myFunc() {
// call this function at the end of the animation.
}
}
html只是一个div
<div class="w9914420">
<h2>
first-component Works!
</h2>
</div>
老实说,我对JavaScript并不太熟悉,所以任何帮助或快速示例都可以帮助我更好地理解Angular 2.
答案 0 :(得分:29)
这是一个有效的例子:
import {Component, NgModule, Input, trigger, state, animate, transition, style, HostListener } from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
@Component({
selector : 'toggle',
animations: [
trigger('toggle', [
state('true', style({ opacity: 1; color: 'red' })),
state('void', style({ opacity: 0; color: 'blue' })),
transition(':enter', animate('500ms ease-in-out')),
transition(':leave', animate('500ms ease-in-out'))
])
],
template: `
<div class="toggle" [@toggle]="show"
(@toggle.start)="animationStarted($event)"
(@toggle.done)="animationDone($event)"
*ngIf="show">
<ng-content></ng-content>
</div>`
})
export class Toggle {
@Input() show:boolean = true;
@HostListener('document:click')
onClick(){
this.show=!this.show;
}
animationStarted($event) {
console.log('Start');
}
animationDone($event) {
console.log('End');
}
}
@Component({
selector: 'my-app',
template: `
<div>
<toggle>Hey!</toggle>
</div>
`,
})
export class App {
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ App, Toggle ],
bootstrap: [ App ]
})
export class AppModule {}
答案 1 :(得分:12)