Categories

Friday, June 21, 2024
#919814419350 therichposts@gmail.com
AngularAngular 17Angular Admin TemplatesAngular TemplatesBootstrap 5Bootstrap 5 TemplatesBootstrap TemplatesFree Admin Dashboard Templates

Creating dashboard with multiple admin and user role type in Angular 17

Creating dashboard with multiple admin and user role type in Angular 17

Hello guys how are you? Welcome back to my blog. Today in this post I am Creating dashboard with multiple admin and user role type in Angular 17

Live Demo

Ensure you have Angular CLI installed. If not, install it using npm install -g @angular/cli.

ng new admin-dashboard
cd admin-dashboard

Install Bootstrap via npm.

npm install bootstrap

Then, add Bootstrap to your angular.json file:

"styles": [
  "node_modules/bootstrap/dist/css/bootstrap.min.css",
  "src/styles.css"
],
"scripts": []
ng generate component login
ng generate component admin-dashboard
ng generate component user-dashboard
ng generate service auth
ng generate component navigation

Update your app-routes.ts to define routes for login, admin, and user dashboards.

import { Routes } from '@angular/router';
import { LoginComponent } from './login/login.component';
import { AdminDashboardComponent } from './admin-dashboard/admin-dashboard.component';
import { UserDashboardComponent } from './user-dashboard/user-dashboard.component';
import { AuthGuard } from './auth.guard';
export const routes: Routes = [
    { path: '', redirectTo: '/login', pathMatch: 'full' },
    { path: 'login', component: LoginComponent },
    { path: 'admin-dashboard', component: AdminDashboardComponent, canActivate: [AuthGuard], data: { role: 'admin' } },
    { path: 'user-dashboard', component: UserDashboardComponent, canActivate: [AuthGuard], data: { role: 'user' } }
];

In auth.service.ts, implement login functionality and role-based access control.

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  private isAuthenticated = false;
  private userRole: string | null = null;

  constructor(private router: Router) { }

  login(username: string, password: string): boolean {
    if (username === 'admin' && password === 'admin') {
      this.isAuthenticated = true;
      this.userRole = 'admin';
      this.router.navigate(['/admin-dashboard']);
      return true;
    } else if (username === 'user' && password === 'user') {
      this.isAuthenticated = true;
      this.userRole = 'user';
      this.router.navigate(['/user-dashboard']);
      return true;
    }
    return false;
  }

  logout(): void {
    this.isAuthenticated = false;
    this.userRole = null;
    this.router.navigate(['/login']);
  }

  isLoggedIn(): boolean {
    return this.isAuthenticated;
  }

  getRole(): string | null {
    return this.userRole;
  }
}

In auth.guard.ts, implement the route guard to check for authentication and roles.

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  private isAuthenticated = false;
  private userRole: string | null = null;

  constructor(private router: Router) { }

  login(username: string, password: string): boolean {
    if (username === 'admin' && password === 'admin') {
      this.isAuthenticated = true;
      this.userRole = 'admin';
      this.router.navigate(['/admin-dashboard']);
      return true;
    } else if (username === 'user' && password === 'user') {
      this.isAuthenticated = true;
      this.userRole = 'user';
      this.router.navigate(['/user-dashboard']);
      return true;
    }
    return false;
  }

  logout(): void {
    this.isAuthenticated = false;
    this.userRole = null;
    this.router.navigate(['/login']);
  }

  isLoggedIn(): boolean {
    return this.isAuthenticated;
  }

  getRole(): string | null {
    return this.userRole;
  }
}

In login.component.ts, handle the login form submission.

import { Component } from '@angular/core';
import { AuthService } from '../auth.service';
import { FormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';

@Component({
  selector: 'app-login',
  standalone: true,
  imports: [CommonModule, FormsModule],
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent {
  username: string = '';
  password: string = '';
  loginFailed: boolean = false;

  constructor(private authService: AuthService) { }

  onLogin(): void {
    this.loginFailed = !this.authService.login(this.username, this.password);
  }
}

  

In login.component.html:

<div class="container">
    <div class="row justify-content-center">
      <div class="col-md-6">
        <h2>Login</h2>
        <form (ngSubmit)="onLogin()">
          <div class="mb-3">
            <label for="username" class="form-label">Username</label>
            <input type="text" class="form-control" id="username" [(ngModel)]="username" name="username" required>
          </div>
          <div class="mb-3">
            <label for="password" class="form-label">Password</label>
            <input type="password" class="form-control" id="password" [(ngModel)]="password" name="password" required>
          </div>
          <button type="submit" class="btn btn-primary">Login</button>
          <div *ngIf="loginFailed" class="mt-3 text-danger">
            Login failed. Please check your credentials.
          </div>
        </form>
      </div>
    </div>
  </div>
  

Create simple templates for these components in their respective HTML files.

admin-dashboard.component.html:

<div class="container">
  <h2>Admin Dashboard</h2>
  <p>Welcome, Admin!</p>
  <div class="row">
    <div class="col-md-4">
      <div class="card">
        <div class="card-body">
          <h5 class="card-title">User Management</h5>
          <p class="card-text">Manage users and their roles.</p>
          <a href="#" class="btn btn-primary">Go to User Management</a>
        </div>
      </div>
    </div>
    <div class="col-md-4">
      <div class="card">
        <div class="card-body">
          <h5 class="card-title">Reports</h5>
          <p class="card-text">View various reports and statistics.</p>
          <a href="#" class="btn btn-primary">View Reports</a>
        </div>
      </div>
    </div>
    <div class="col-md-4">
      <div class="card">
        <div class="card-body">
          <h5 class="card-title">Settings</h5>
          <p class="card-text">Adjust application settings.</p>
          <a href="#" class="btn btn-primary">Go to Settings</a>
        </div>
      </div>
    </div>
  </div>
</div>

user-dashboard.component.html:

<div class="container">
  <h2>User Dashboard</h2>
  <p>Welcome, User!</p>
  <div class="row">
    <div class="col-md-4">
      <div class="card">
        <div class="card-body">
          <h5 class="card-title">Profile</h5>
          <p class="card-text">View and edit your profile information.</p>
          <a href="#" class="btn btn-primary">Go to Profile</a>
        </div>
      </div>
    </div>
    <div class="col-md-4">
      <div class="card">
        <div class="card-body">
          <h5 class="card-title">Tasks</h5>
          <p class="card-text">Manage your tasks and to-dos.</p>
          <a href="#" class="btn btn-primary">View Tasks</a>
        </div>
      </div>
    </div>
    <div class="col-md-4">
      <div class="card">
        <div class="card-body">
          <h5 class="card-title">Messages</h5>
          <p class="card-text">Check your messages and notifications.</p>
          <a href="#" class="btn btn-primary">View Messages</a>
        </div>
      </div>
    </div>
  </div>
</div>

navigation.component.html:

<nav class="navbar navbar-expand-lg navbar-light bg-light">
    <a class="navbar-brand" routerLink="/">Dashboard</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarNav">
      <ul class="navbar-nav ml-auto">
        <li class="nav-item">
          <a class="nav-link" routerLink="/">Admin Dashboard</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" routerLink="/">User Dashboard</a>
        </li>
        <li class="nav-item">
          <button class="btn btn-link nav-link" (click)="logout()">Logout</button>
        </li>
      </ul>
    </div>
  </nav>
  

navigation.component.ts:

import { Component } from '@angular/core';
import { AuthService } from '../auth.service';
import { FormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';

@Component({
  selector: 'app-login',
  standalone: true,
  imports: [CommonModule, FormsModule],
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent {
  username: string = '';
  password: string = '';
  loginFailed: boolean = false;

  constructor(private authService: AuthService) { }

  onLogin(): void {
    this.loginFailed = !this.authService.login(this.username, this.password);
  }
}

Update app.component.html to include the navigation component.

<app-navigation></app-navigation>
<router-outlet></router-outlet>

Finally, run your application to test the functionality.

ng serve
Creating dashboard with multiple admin and user role type in Angular 17
Creating dashboard with multiple admin and user role type in Angular 17
user login dashboard
user login dashboard
Login page with validation
Login page with validation

Now, your application should have a login page, and based on the credentials entered, it should redirect users to either the admin or user dashboard, enforcing role-based access control using Angular’s routing and guards.

Note: Friends, In this post, I just tell the basic setup and things, you can change the code according to your requirements.

I will appreciate that if you will tell your views for this post. Nothing matters if your views will be good or bad because with your views, I will make my next posts more good and helpful.

Jassa

Thanks

therichpost
the authortherichpost
Hello to all. Welcome to therichpost.com. Myself Ajay Malhotra and I am freelance full stack developer. I love coding. I know WordPress, Core php, Angularjs, Angular 14, Angular 15, Angular 16, Angular 17, Bootstrap 5, Nodejs, Laravel, Codeigniter, Shopify, Squarespace, jQuery, Google Map Api, Vuejs, Reactjs, Big commerce etc.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.