Search code examples
angulartypescriptauthenticationuser-rolesangular-ng-if

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.


Solution

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