Search code examples
angularngforangular-ng-if

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.

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.

Now i'd like to check with *ngIf if the Object i pushed to NaviEntries is allowed to show at the Navi

Can i use an Object Value as an Variable used in my Component??

Excample:

NaviEntry => {name: 'Admin', link: '/admin', role: 'admin'}

In my Component => admin: boolean = true;

Template:

*ngIf="{{entry.role}}" => *ngIf="admin" => true => show item


Solution

  • 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

    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]"