问题描述
我有一个角度2的测试应用程序构建,我已经成功地在路线更改之间应用了一个动画
I have a test app build with angular 2, I have successfully applied one animation between route change
state('default', style({
opacity: 1,
transform: 'scale(1) translateY(0)'
})),
transition('void <=> default', [
style({ opacity: 0, transform: 'scale(.9) translateY(-20px)' }),
animate('.2s')
])
但是当列表页面更改为项目页面时,我也想要一个不同的动画,例如单击英雄列表中的英雄,所以我这样做了
But I also want a different animation when a list page change to an item page, like click a hero inside a hero-list, so I did this
state('childActivate', style({
opacity: 1,
transform: 'scale(1) translateY(0)'
})),
transition('childActivate => void', [
animate('1.2s', style({
transform: 'scale(0.9) translateY(-120px)',
opacity: 0
}))
])
在我单击一个项目之后并在导航之前,我试图将状态设置为"childActivated":
I tried to set the state to 'childActivated' after i click on an item and before navigation:
onHeroSelected(heroEvent: Hero) {
this.animState = "childActivate";
this.router.navigate(['/hero-detail', heroEvent.id]);
}
但没有效果.
如何在路线之间获得多个动画?
How can I get multiple animations between route?
推荐答案
将状态设置为"childActivate"无效,因为该组件在下一个更改检测步骤中已被破坏,因此状态改为改为void.
Setting the state to "childActivate" has no effect, because the component is being destroyed within the next change detection step, so state switches to void instead.
这是我解决此问题的方法:我将路线更改延迟了1个进一步的更改检测周期.为此,我使用了CanDeactivate Guard,它侦听了解决的承诺.
This is how i solved this issue:I delay the route change by 1 further change detection cycle. I use a CanDeactivate Guard for this, which listens for a promise to resolve.
查看我的plnkr: https://embed.plnkr.co/cOeDfXCetaYuXFaZ7WeO/
Check out my plnkr:https://embed.plnkr.co/cOeDfXCetaYuXFaZ7WeO/
我在路线定义中添加:
canDeactivate: [CanDeactivateAfterChangeDetectionGuard]
这是CanDeactivate Guard:
This is the CanDeactivate Guard:
@Injectable()
class CanDeactivateAfterChangeDetectionGuard implements CanDeactivate<WaitForChangeDetection> {
canDeactivate(component: WaitForChangeDetection): Promise<boolean> {
return component.waitForChangeDetection();
}
}
可与实现此接口的任何组件一起使用:
which works with any component implementing this interface:
declare abstract class WaitForChangeDetection {
abstract waitForChangeDetection(): Promise<boolean>;
}
我使用此接口的默认实现创建了一个基本组件
I created a base component with a default implementation of this interface
@Component({})
class WaitForChangeDetectionImpl implements AfterViewChecked, WaitForChangeDetection {
constructor(private cdRef: ChangeDetectorRef){
this.viewChecked$ = new Subject<void>();
}
viewChecked$: Subject<void>;
waitForChangeDetection(): Promise<boolean>{
this.cdRef.detectChanges();
return new Promise((resolve) => this.viewChecked$.subscribe(() => resolve(true)));
}
ngAfterViewChecked(){
this.viewChecked$.next();
}
}
因此,您可以扩展此组件,以提供可与任何组件的防护罩一起使用的功能.
So you can extend this component to provide the functionality to work with the guard for any component.
@Component({})
class ComponentA extends WaitForChangeDetectionImpl {
...
这篇关于如何在角度2的不同路线之间应用不同的动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!