在某些动态路由中隐藏 Angular 中的组件

hide component in Angular in certain dynamic route

我需要在登录到我的管理面板时从我的主页隐藏某些组件,例如导航栏和页脚。我的管理组件在调用时基于管理模块延迟加载。如果路由不是动态的,例如 /admin/login/admin/dashboard 等,那么在管理员视图中,必要的组件将按预期隐藏。但是如果路由是动态的,例如 /admin/category/:categoryId/admin/user/:userId 并且在这些路由中,导航栏和页脚等必要组件不会自行隐藏。我在必要的组件中使用 ActivatedRoute 获取路由的动态 ID。下面是我在主页上使用的方法来相应地读取应用程序路由和 show/hide 组件。

Main.ts

 import { Router, NavigationEnd } from '@angular/router';

  public url: any;

  constructor(private router: Router) {

    this.router.events.subscribe((event) => {
      if (event instanceof NavigationEnd) {
        this.url = event.url;
      }
    })
  }

Main.html

<div class="main__container">
  <app-navbar
    *ngIf="url !== '/admin' && url !== '/admin/dashboard' && url !== '/admin/post-article' && url !== '/admin/video' && url !== '/admin/login' && url !== '/admin/sign-up' && url !== '/admin/category/:categoryId'">
  </app-navbar>
  <app-footer
    *ngIf="url !== '/admin' && url !== '/admin/dashboard' && url !== '/admin/category/:categoryId' && url !== '/admin/post-article' && url !== '/admin/video' && url !== '/admin/login' && url !== '/admin/sign-up'">
  </app-footer>
</div>

您在这里需要的是定义正则表达式并针对它们进行测试。 或者检查 string#includes(string) 函数就足够了。我还建议使用更 反应性 (类似 rxjs)的方法。

在我的模板上我会:


<div class="main__container">
  <app-navbar *ngIf="canShowNavBar$ | async">
  </app-navbar>
  <app-footer *ngIf="canShowFooter$ | async">
  </app-footer>
</div>

打字稿文件中的什么位置:

export class YourComponent implements OnInit {

   canShowNavBar$: Observable<boolean>;
   canShowFooter$: Observable<boolean>;
   navigationEvents$: Observable<NavigationEnd>;


   constructor(private router: Router){}

   ngOnInit() {
     // Like this we define the stream of the NavigationEnd events
     this.navigationEvents$ = this.router.events.pipe(
        filter(event => event instanceof NavigationEnd),
        // This one is not really needed but we're giving some hints to the typescript compiler
        map(event => event as NavigationEnd) 
      );
      // Here we define the stream of booleans that determine whether to show the component or not on your template.
      this.canShowNavBar$ = this.navigationEvents$.pipe(
         map(event => this.shouldShowNavBar(event.url))
      );
      // Because actually you check for the same conditions
      this.canShowFooter$ = this.canShowNavBar$;
   }

   shouldShowNavBar(url: string): boolean {
      // And here you should test against regular expressions:
     switch(true) {
        case /\/admin\/dashboard/.test(url):
        case /\/admin\/category/.test(url):
        // More cases where you should show the navBar
           return true;
        default: return false;
     }



   }
   
}

您可以阅读更多关于 Regular Expressions on JavaScript here

实现 shouldShowNavBar 的另一种方法是使用一些数组谓词,如 some:像这样:


shouldShowNavBar(url: string): boolean {
   const conditions = [
      !url.startsWith('/admin/dashboard'),
      !url.includes('/admin/category'),
      // More conditions?
   ];
   return conditions.some(isTrue => isTrue);
}

如果您不想使用异步,请保持代码不变,但请执行以下操作:


<div class="main__container">
  <app-navbar *ngIf="shouldDisplayNavBar(url)">
  </app-navbar>
  <app-footer *ngIf="shouldDisplayNavBar(url)">
  </app-footer>
</div>


shouldShowNavBar(url: string): boolean {
   if(!url) {
     return false;
   }

   const conditions = [
      !url.startsWith('/admin/dashboard'),
      !url.includes('/admin/category'),
      // More conditions?
   ];
   return conditions.some(isTrue => isTrue);
}

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'my-component',
  templateUrl: './my.component.html',
  styleUrls: ['./my.component.scss']
})
export class MyComponent implements OnInit {

  constructor(
    private router: Router,
  ) {}

  ngOnInit() {
  }


  /**
   * Check if the router url contains the specified route
   *
   * @param {string} route
   * @returns
   * @memberof MyComponent
   */
  hasRoute(route: string) {
    return this.router.url.includes(route);
  }
}
<!-- First view -->
<div *ngIf="hasRoute('home')">
    First View
</div>

<!-- Second view activated when the route doesn't contain the home route -->
<div *ngIf="!hasRoute('home')">
    Second View
</div>