how to apply different animation between different route in angular 2

走远了吗. 提交于 2019-11-29 15:33:23

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.

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.

Check out my plnkr: https://embed.plnkr.co/cOeDfXCetaYuXFaZ7WeO/

Within route definitions i add:

canDeactivate: [CanDeactivateAfterChangeDetectionGuard]

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 {
...
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!