可选择在Angular App中显示导航栏

问题描述 投票:0回答:1

AngularJS的初学者。 我想选择性地显示我的侧边导航栏。所以说我有5个组件Home,SideBar,Page1,Page2和Page3。如果在Home或Page2上显示SideBar,但如果在Page1或Page3上不显示。在我的app.component.html中的一些伪代码,我想这样。

<app-sidebar></app-sidebar>  //Display for Home, Page2
<router-outlet></router-outlet>

什么是最好的实践方式,什么是快速和肮脏的方式来实现呢?我已经看到了类似的行为,在登录页面的上下文中使用CanActivate,但无法真正弄清楚它将如何满足我的需求。

angular navbar
1个回答
1
投票

定义服务并编写一个通用的方法来设置一个变量的值。

class helperService {

 public bSubject: BehaviorSubject<boolean> = new BehaviorSubject(true);

    setNavBar(val){
       this.bSubject.next(val);
    }
 public getNavBar(): boolean {
        return this.bSubject.value;
    }
}

在每个组件中

 if (this.helperService.getNavBar()) {
      this.show=true;
    }else{
this.show=false;
}

并根据

ngOninit(){

this.helperService.setNavBar(false);
}

0
投票

以下是实现这一目标的最佳优化方法,无需对现有的组件代码进行太多修改,也能让其他组件更容易启用侧边栏。

配置你的路由器。

  {
    path: "home",
    component: HomeComponent,
    canActivate: [AuthGuard],
    data: { sidebar: true }
  },

创建一个SidebarService来更新路由的特定值。

@Injectable({
    providedIn: "root"
})
export class SidebarService {

  private showSidebar$ = new BehaviorSubject<Boolean>(false);

  constructor() { }

  setValue(value: boolean) {
    this.showSidebar$.next(value);
  }

  getValue() {
    this.showSidebar$.value;
  }

  getValue$() {
    this.showSidebar$.asObservable;
  }

}

现在在你的AuthGuard

@Injectable({
   providedIn: "root"
  })
 export class AuthGuard implements CanActivate, CanActivateChild, CanDeactivate<any> {

   constructor(private router: Router,
    private sidebarService : SidebarService ) { }

   canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
     const showSidebar = route["data"]["sidebar] || false;
     this.sidebarService.setValue(showSidebar );
  }
}

现在在选择器中添加*ngIf,并在组件中注入SidebarService服务。

在组件中

constructor(private sidebarService : SidebarService ) { }

get showSideBar(){
  return this.sidebarService.getValue$();
}

在HTML中

<app-sidebar *ngIf="showSideBar | async"></app-sidebar> // Use either async pipe or you can have a variable and updating its value by subscribing to this.sidebarService.getValue$()

现在你只需要添加

data: { sidebar: true }

在你想启用侧栏的路径中。这是我知道的最好的优化方式,可能对你也有用。

© www.soinside.com 2019 - 2024. All rights reserved.