Mohamed Wahshey
Mohamed Wahshey

Reputation: 422

How to show/hide element depending on user role Angular 4

I'm working on a project which has more than one user type (SuperUser - SchoolAdmin - Teacher)

And each role has privilige to see some elements.

How do i hide elements depending on the logged user role using *ngIf?

This is the project link on Stack-blitz, i uploaded some of it to guide me with the live preview.

Inside app you will find common services >> auth, this is the folder which has login service and authentication guard.

Inside models >> enum, you will find user type enum.

Inside component sign-in you will find the form which defines user type.

Inside routes you will see the expected roles made for each component.

Users that i made for testing:

This should route you to the school-list

Admin (which has super user role): [email protected] Password: 12345

This should route you to the dashboard

Student (which has student role): [email protected] Password: 12345

For example is i want to hide element on the dash-board to be only shown to the super user role, how can i do this?

I know that there is a way with ngIf but i'm stuck on the right way to write it inside the NgIf, i want examples on my code not a dummy code.

Update: issue has been resolved so i deleted the users made for testing.

Upvotes: 2

Views: 24110

Answers (3)

carton
carton

Reputation: 1168

In your project, when a user is registering you are asking if he is a 'Teacher', 'Parent' or a 'Student'. So here you have your condition.

When you sign-in or register you should save your user data somewhere (in a service for exemple which you can use with @injection.

Then with that data you should make some test in your DOM like this:

/* if type_id == id(student) */
 <div *ngIf="myService.currentUser.type_id">
   // your student display ...
 </div>

 /* if type_id == id(teacher) */
 <div *ngIf="myService.currentUser.type_id">
   // your teacher display ...
 </div>

Is this helping you ? You should read this docs Services

[Exemple in your case]

Your service:

import { Injectable } from '@angular/core';
/*
   other import 
*/

 @Injectable()
 export class UserService {

      public currentUser: any;

      constructor(){}

      public login(loginData: LoginModel): any {
            const apiUrl: string = environment.apiBaseUrl + '/api/en/users/login';  
            let promise = new Promise((resolve, reject) => { // this is a  promise. learn what is a promise in Javascript. this one  is only more structured in TypeScript
  // a promise is returned to make sure that action is taken only after the response to the api is recieved
             this.http.post(apiUrl, loginData).subscribe((data: any) => {
                if(data.status)
                {
                  var userData = {
                      token: data.token,
                      user:data.user 
                     };
                this.currentUser = data.user // HERE SAVE YOUR user data
                return resolve(userData);
                }
                else {
                       return reject(data)
                 }
               }, (err: HttpErrorResponse) => {
               return reject(err);
            });
          });
     return promise;
      }
 }

Then inject that service in your constructor and your service in

Component:

// Don't forgot to import UserService !!
constructor(public userService: UserService){}

DOM:

*ngIf="userService.currentUser.type_id == 1"

Upvotes: 5

Joe Belladonna
Joe Belladonna

Reputation: 1339

You should do:

<div *ngIf="superUserLogged">
   // your SuperUser display ...
 </div>
<div *ngIf="schoolAdminLogged">
       // your SuperUser display ...
</div>
<div *ngIf="teacherLogged">
       // your SuperUser display ...
</div>

and in *.ts file when ever someone logs to system you do:

onLogin(userrLogged: string) {
    this.superUserLogged  = false;
    this.schoolAdminLogged = false;
    this.teacherLogged = false;
    switch (userrLogged) {
        case 'SuperUser':
            this.superUserLogged = true;
            break;
        case 'SchoolAdmin':
            this.schoolAdminLogged = true;
            break;
        case 'Teacher':
            this.teacherLogged = true;
            break;
}

Upvotes: 0

Sangeeth John
Sangeeth John

Reputation: 330

boolean value true or false is used for hiding. In HTML file <div *ngIf = !test>_contents to be printed_</div> In .ts file initialize test = false; so whenever this.test = true; div will show otherwise will be in hide . Check your condition and make the test = true;

Upvotes: 0

Related Questions