在我的应用程序中,我试图根据用户的角色实现navbar。如果用户是管理员,则应显示不同的菜单,对于普通用户,它应仅显示用户的菜单。我正在使用ngSwitch来限制导航栏但是无法做到。请看看。
<div [ngSwitch] = "myrole">
<ng-template *ngSwitchCase = "'Admin'">
<nav class="navbar navbar-expand-sm bg-primary navbar-dark">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link" routerLink = '/home' routerActive = 'active'>Home</a>
</li>
<li class="nav-item">
<a class="nav-link" routerLink = '/logout' routerActive = 'active' >Log Out</a>
</li>
<li class="nav-item" style="text-align:right">
<span class="nav-link navbar-right">{{username}}</span>
</li>
</ul>
</nav>
</ng-template>
<ng-template *ngSwitchCase = "'NoUser'">
<nav class="navbar navbar-expand-sm bg-primary navbar-dark">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link" routerLink = '/home' routerActive = 'active'>Home</a>
</li>
<li class="nav-item">
<a class="nav-link" routerLink = '/login' routerActive = 'active' >Login</a>
</li>
<li class="nav-item">
<a class="nav-link" routerLink = '/signup' routerActive = 'active' >Sign UP</a>
</li>
</ul>
</nav>
</ng-template>
</div>
答案 0 :(得分:1)
您的语法错误,更改
发件人强>
<ng-template *ngSwitchCase = "'Admin'">
要强>
<ng-template [ngSwitchCase] = "'Admin'">
答案 1 :(得分:0)
使用ng-template,您需要使用属性绑定而不是结构绑定。所以改变 的 FROM 强>
<ng-template *ngSwitchCase = "'Admin'">
到
<ng-template [ngSwitchCase] = "'Admin'">
或强> 还有另一种解决方案
使用ngSwitchCase作为结构指令,但没有ng-template,即
<div *ngSwitchCase = "'Admin'">
答案 2 :(得分:0)
这是代码
HTML模板是
<div [ngSwitch] = "myrole">
<ng-template [ngSwitchCase] = "'Admin'">
<nav class="navbar navbar-expand-sm">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" >Log Out</a>
</li>
<li class="nav-item" style="text-align:right">
<span class="nav-link navbar-right">{{'Test'}}</span>
</li>
</ul>
</nav>
</ng-template>
<ng-template [ngSwitchCase] = "'NoUser'">
<nav class="navbar navbar-expand-sm">
<ul class="navbar-nav">
<li class="nav-item active">
<a href="/">Home</a>
</li>
<li class="nav-item">
<a href="/">Login</a>
</li>
<li class="nav-item">
<a href="/">Sign Up</a>
</li>
</ul>
</nav>
</ng-template>
</div>
ts档
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-switch-exampl',
templateUrl: './switch-exampl.component.html',
styleUrls: ['./switch-exampl.component.css']
})
export class SwitchExamplComponent implements OnInit {
myrole: string = 'Admin'
constructor() { }
ngOnInit() {
}
}
答案 3 :(得分:0)
对不起伙计我的坏人。角色来自服务,它在初始化组件时将角色初始化为空字符串。所以作为一个解决方案,我添加了另一个这样的部分
<ng-template [ngSwitchCase] = "''">......</ng-template>
感谢您的建议。