* ngIf if you find a value in an angular array 4

0

How can I do the ngIf with the condition that it shows the element if it finds an element in an array, be it a string or a string,

I do not have anything on the internet

I tried * nfIf="userModel.roles.find (x = > x.name == 'administrator')" error, error and error, I can not find how to solve this big problem, it took a while.

The user model I have is

export class User{
    constructor(
        public id: number,
        public email: string,
        public password: string,
        public name: string,
        public roles: Array<any>,
        public permissions: Array<any>,

    ){



    }
}

and yet when putting // Property calculated in the Model get isAdmin (): boolean {     this.roles.findIndex (role = > role.name === 'administrator') > -one;   } I get errors like in isAdmin

also using that as a method in the component does not work either

checkRoles(){
    if(this.userModel.roles.findIndex(role => role.name === 'administrator') > -1){
      this.isAdmin = true;
    }
  }

initially isAdmin is false. Did you test that on angular 4 or 5?

an example is nothing more to hide this menu depending on the role of the user (can have several roles)

<li class="nav-item dropdown">
                <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true"
                    aria-expanded="false">
                Usuarios
              </a>
                <div class="dropdown-menu" aria-labelledby="navbarDropdown">
                    <a class="dropdown-item" [routerLink]="['/users']">Ver usuarios</a>
                    <a class="dropdown-item" [routerLink]="['/users/add']">Agregar usuario</a>
                </div>
            </li>

I just want to hide it if the user's roles have at least administrator but not show it. that is the example

    
asked by santiago 11.03.2018 в 08:14
source

1 answer

2

The best thing you can do is a property calculated in the User class / model, instead of your business logic in the view, the view should arrive "all chewed".

// Propiedad calculada en el Modelo
get isAdmin(): boolean {
  this.roles.findIndex(role => role.name === 'administrator') > -1;
}
// En tu Vista
*ngIf="userModel.isAdmin"
    
answered by 11.03.2018 в 08:31