Showing or hiding elements based on user roles in Angular 4

I am currently working on a project that involves multiple user types (SuperUser - SchoolAdmin - Teacher).

Each role has specific privileges to access certain elements.

How can I dynamically hide elements based on the logged-in user's role using *ngIf?

Here is the link to the project on StackBlitz, where I have provided a live preview for guidance.

In the app, you will find common services under auth. This folder contains the login service and authentication guard.

Check out models >> enum to see the user type enum.

In the sign-in component, you will find the form that defines the user type.

Review the routes to see the expected roles assigned to each component.

Testing users:

This user should be directed to the school-list page

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

This user should be directed to the dashboard

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

For instance, if I want to hide an element on the dashboard visible only to the super user role, how can I achieve this?

I understand that I can use ngIf, but I am unsure of the correct way to implement it within NgIf. I need practical examples based on my code.

Update: The issue has been resolved, so I have removed the test users.

Answer №1

When registering a user in your project, you prompt them to specify if they are a 'Teacher', 'Parent', or 'Student'. This information can be used as a condition.

Upon signing in or registering, it is important to store the user data in a designated location, such as a service that can be accessed using @injection.

Subsequently, you can perform tests on the DOM utilizing this stored data:

/* If type_id == id(student) */
<div *ngIf="myService.currentUser.type_id">
   // Display for student...
</div>

 /* If type_id == id(teacher) */
<div *ngIf="myService.currentUser.type_id">
   // Display for teacher...
</div>

Is this guidance beneficial? It could be helpful to refer to the documentation found here.

[Example specific to your scenario]

Your Service:

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

 @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.http.post(apiUrl, loginData).subscribe((data: any) => {
                if(data.status)
                {
                  var userData = {
                      token: data.token,
                      user:data.user 
                     };
                this.currentUser = data.user // Save user data here
                return resolve(userData);
                }
                else {
                       return reject(data)
                 }
               }, (err: HttpErrorResponse) => {
               return reject(err);
            });
          });
     return promise;
      }
 }

Remember to inject this service in your constructor and your service in

Component:

// Ensure UserService has been imported !!
constructor(public userService: UserService){}

DOM:

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

Answer №2

When it comes to hiding content, a boolean value of either true or false is typically utilized. In an HTML file, you can use the following code snippet:

<div *ngIf = !test>_contents to be printed_</div>
. Additionally, in the corresponding .ts file, you should initialize the variable test as false like so: test = false;. Then, by setting this.test = true;, the div will become visible. Otherwise, it will remain hidden. Be sure to carefully evaluate your condition and set test = true; accordingly.

Answer №3

Here is a suggestion for your code:

<div *ngIf="superUserLoggedIn">
   // display content for SuperUser...
 </div>
<div *ngIf="schoolAdminLoggedIn">
       // display content for School Admin...
</div>
<div *ngIf="teacherLoggedIn">
       // display content for Teacher...
</div>

To implement this in the *.ts file, you can use the following function when someone logs into the system:

onLogin(userType: string) {
    this.superUserLoggedIn = false;
    this.schoolAdminLoggedIn = false;
    this.teacherLoggedIn = false;
    switch (userType) {
        case 'SuperUser':
            this.superUserLoggedIn = true;
            break;
        case 'SchoolAdmin':
            this.schoolAdminLoggedIn = true;
            break;
        case 'Teacher':
            this.teacherLoggedIn = true;
            break;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to retrieve a value from a base64-decoded string in Angular 6?

I successfully decoded a Base64 string using the xml2js library and obtained the following XML value: <?xml version="1.0" encoding="UTF-8" standalone="no"?> <svg width="293" height="102" viewBox="0 0 293 102" xmlns="http://www.w3.org/2000/svg" ...

Organizing a collection of bags using ng2-dragula technology

I have successfully implemented ng2-dragula for a dynamic sorting user interface. Currently, I can reorder the <li> elements within each container. <div *ngFor="let bag of chest" class='container'> <ul [dragula]='"bag-one"& ...

Issue with upgrading node from 12v to 16v: Trying to access a property that does not exist, specifically 'splice', within a circular dependency in module exports

After upgrading the node version from 12 to 16, we encountered a debugging console error. The 'Promises' are failing to resolve following this error, leading to the termination of further execution. (node:28112) Warning: Accessing non-existent p ...

When attempting to access the property 'originalname' of an undefined nodejs Mongoose object, an error is triggered

I am attempting to save images using mongoose, express, and multer. However, I keep encountering the following error when testing with Postman: TypeError: Cannot read property 'originalname' of undefined var express=require("express") var ro ...

Troubleshooting issue with beforeEach in karma and Mocha after upgrading to Angular 4

Unique Context After verifying the successful "green" builds on the master branch, which utilizes angular-cli 1.0.0 and the older angular2 dependencies, my goal is to transition from angular2 to angular4. Issue Post Upgrade The application functions pr ...

Angular triggers a reload of iframe content whenever there is a manipulation of the DOM

One of the challenges I'm facing is with dynamically loading an iframe when a specific condition is met. <div *ngIf="iframeData"> <iframe [src]="sanitizer.bypassSecurityTrustResourceUrl(iframeData.iFrameUrl)" name="paymetricIFr ...

The mark-compacts were not efficient enough, they approached the heap limit and as a result, the allocation failed. The JavaScript

Currently working with Angular version 7.2 and encountering an issue when running ng serve: FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory What does this error mean? How can it be resolved? The ...

Angular: Understanding Render Delay Caused by *ngIf and Expression Changes from Filters

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'ngIf: false'. Current value: 'ngIf: true'. Encountering the above error in the console. In my code, I have filters that control ...

Create a new instance of the TypeScript singleton for each unit test

I have a TypeScript singleton class structured like this: export default class MySingleton { private constructor({ prop1, prop2, ... }: MySingletonConfig) { this.prop1 = prop1 ?? 'defaultProp1'; this.prop2 = prop2; ...

Am I on track with this observation?

I am currently using the following service: getPosition(): Observable<Object> { return Observable.create(observer => { navigator.geolocation.watchPosition((pos: Position) => { observer.next(pos); observer.c ...

Angular Service Singleton Utilized in Components

I have a structural question regarding my Angular application. I am following the widely-used core, shared, and feature modules structure, similar to the one found here. In my core module, I have a singleton notification service defined, but I use a custom ...

How to Invoke a Function from Entry Component to Parent Component in Angular 7

My module includes the DragDropComponent in entry components, where the parent component consumes it like this: Parent Component: upload(data) { const modalRef = this.model.open(DragNDropComponent, { data: data, panelClass: 'defa ...

I am unable to log in, even though there are users saved in the database

I'm currently working on implementing a user login system for a website. Users can register successfully, but when attempting to log in, an error message pops up stating that there is no user with that email. I'm confused about what might be caus ...

The function with which you are trying to use 'new' does not have a call or construct signature

How can I prevent the error from appearing in my console.log? An error message - 'Cannot use 'new' with an expression whose type lacks a call or construct signature.' - keeps popping up. var audioContext = new window.AudioContext() ...

Looking for Angular 2 material components for dart with CSS styling? Need help centering a glyph on your page?

HTML: <div class="border"> <glyph class="center" [icon]="'star'" ></glyph> <div class="centerText"> This Is Text that is centered. </div> </div> Css: .centerText{ text-align: center ...

Encountering a Webpack compilation error following the installation of a new package

I am currently working with a boilerplate code for Angular 4 and encountering an issue. Everything was functioning properly until I downloaded a new package from npm. After doing so, I started receiving the following error message and the command ng serve ...

Error encountered in Nest.js tests due to dependency injection issues between modules. The module 'src/foo/foo.module' cannot be located from 'bar/bar.service.spec.ts'

Encountering an error message Cannot find module 'src/foo/foo.module' from 'bar/bar.service.spec.ts' while testing a service that relies on another module. I am facing difficulty in setting up the test scenario for a Nest.js project wi ...

What is the method to insert a new <input> element after the last input field has been filled in

I recently started working on a form using StackBlitz, but I've hit a roadblock and need some guidance on how to proceed. My goal is to achieve a similar effect like the one shown in this gif: https://i.stack.imgur.com/76nsY.gif and I'd like to ...

Mocking a third-party callback function in Jest for method implementation

Utilizing Nest + Cognito for user authentication in an application, I have a method within my Authentication service that requires testing/mocking: async cognitoRegister(userPool: CognitoUserPool, { name, password, email }: AuthRegisterInput): ...

Title: How to Build a Dynamic Logo Carousel with React and CSS without External Dependencies

Currently, I am in the process of integrating a logo carousel into my React web application using CSS. My goal is to create a slider that loops infinitely, with the last logo seamlessly transitioning to the first logo and continuing this cycle indefinitely ...