[英]Angular2 *ngIf with a value from Object inside *ngFor
Id like to use a *ngIf inside a *ngFor where my role value is defined for that element. 我想在* ngFor内使用* ngIf,其中为该元素定义了我的角色值。
My Template looks like that: 我的模板如下所示:
<li class="nav-item" *ngFor="let entry of naviEntries">
<button *ngIf="{{entry.role}}" ...>{{entry.name}}</button>
</li>
And inside my Component: 在我的组件中:
enter code here`export class NaviComponent implements OnInit {
naviEntries: NaviEntry[];
visitor: boolean = true;
user: boolean = false;
admin: boolean = false;
constructor() { ... }
ngOnInit() {
...
this.naviEntries.push({name: 'Home', link: '', role: 'visitor'});
this.naviEntries.push({name: 'User', link: '/user', role: 'user'});
this.naviEntries.push({name: 'Admin', link: '/admin', role: 'admin'});
...
Inside the ngOnInit function im checking for if User is logged in or user is an admin. 在ngOnInit函数中,im检查用户是否已登录或用户是管理员。
Now i'd like to check with *ngIf if the Object i pushed to NaviEntries is allowed to show at the Navi 现在我想用* ng检查是否允许我推送到NaviEntries的对象显示在Navi上
Can i use an Object Value as an Variable used in my Component?? 我可以使用对象值作为组件中使用的变量吗?
Excample: Excample:
NaviEntry => {name: 'Admin', link: '/admin', role: 'admin'}
NaviEntry =>
{name: 'Admin', link: '/admin', role: 'admin'}
In my Component => admin: boolean = true; 在我的Component => admin中:boolean = true;
Template: 模板:
*ngIf="{{entry.role}}"
=> *ngIf="admin" => true => show item *ngIf="{{entry.role}}"
=> * ngIf =“ admin” => true =>显示项目
I think you need something like : 我认为您需要类似的东西:
*ngIf="(entry.role === 'admin' && admin) || (entry.role === 'visitor' && visitor) || (entry.role === 'user' && user)"
Please read : 请阅读 :
https://angular.io/api/common/NgIf https://angular.io/api/common/NgIf
As you are using it bit wrong way. 当您使用它时,方法有点错误。
Optimised way to do : 优化的方式:
// component side
roleAccess = {'admin' : false , 'user' : false , 'visitor' : true}
// template side
*ngIf="roleAccess[entry.role]"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.