Angular 2 router ngIf 动态路由

Angular 2 router ngIf dynamic route

如何ngIf动态路由器?例如,我有 top navigation component,它有 back button,我希望 back button 只是在 'item/:id' 路线上可见:

*ngIf="router.url == '/item' or '/item/:id' - 它不起作用。

如何*ngIf动态路由?

你可以建造路线守卫。 canActivate 守卫打开标志,canDeactivate 关闭标志。然后导航项将绑定到该标志。

或者您可以添加一个路由偶数观察器来观察特定事件并转 on/off 一个您可以绑定的标志。

在这个例子中,我使用路由事件来打开 on/off 一个标志来管理微调器:

  constructor(private authService: AuthService,
              private router: Router,
              private messageService: MessageService) {
    router.events.subscribe((routerEvent: Event) => {
      this.checkRouterEvent(routerEvent);
    });
  }

  checkRouterEvent(routerEvent: Event): void {
    if (routerEvent instanceof NavigationStart) {
      this.loading = true;
    }

    if (routerEvent instanceof NavigationEnd ||
        routerEvent instanceof NavigationCancel ||
        routerEvent instanceof NavigationError) {
      this.loading = false;
    }
  }

您可以执行类似的操作来监视一组特定路线的 NavigationStart 事件。例如(没试过):

  constructor(private authService: AuthService,
              private router: Router,
              private messageService: MessageService) {
    router.events.subscribe((routerEvent: Event) => {
      this.checkRouterEvent(routerEvent, router.url);
    });
  }

  checkRouterEvent(routerEvent: Event, routerUrl: string): void {
    if (routerEvent instanceof NavigationStart && routerUrl == '/item') {
      this.myflag= true;
    }

    if (routerEvent instanceof NavigationEnd ||
        routerEvent instanceof NavigationCancel ||
        routerEvent instanceof NavigationError) {
      this.myflag= false;
    }
  }