Side bar disappears after navigation to the dashboard section

  angular, javascript, sidebar, typescript

I have an issue that I’ve been trying to resolve on an angular application I’m assessing. When I navigate to the dashboard section the side bar disappears which should not happen and when I try to navigate to the rest of the menus, the sidebar remains as expected. I have recorded a video to illustrate the problem here.

Output

enter image description here

Side bar should appear as below

enter image description here

Roles

  Admin = 1,
  Voter = 2

Note
I attempted to remove the *ngIf="userType === 1" from the div that is wrapping everything on the sidebar I get the results below, all the content in the sidebar disappears except logout

enter image description here

sidebar-items.ts

import { RouteInfo } from './sidebar.metadata';
export const ROUTES: RouteInfo[] = [

  // Admin Modules

  {
    path: '/admin/dashboard/main',
    title: 'Dashboard',
    moduleName: 'dashboard',
    iconType: 'flaticon-bar-chart',
    icon: '',
    class: 'navigation__active',
    groupTitle: false,
    badge: '',
    badgeClass: '',
    role: [1],
    submenu: [
      // {
      //   path: '/admin/dashboard/main',
      //   title: 'Dashboard',
      //   moduleName: 'dashboard',
      //   iconType: '',
      //   icon: '',
      //   class: 'navigation__active',
      //   groupTitle: false,
      //   badge: '',
      //   badgeClass: '',
      //   role: ['1'],
      //   submenu: [],
      // },

    ],
  },


  {
    path: '',
    title: 'Elections',
    moduleName: 'elections',
    iconType: 'ti-archive',
    icon: '',
    class: 'navigation__active',
    groupTitle: false,
    badge: '',
    badgeClass: '',
    role: [1],
    submenu: [
      {
        path: '/settings/election-setup',
        title: 'Elections Setup',
        moduleName: 'elections',
        iconType: '',
        icon: '',
        class: 'navigation__sub',
        groupTitle: false,
        badge: '',
        badgeClass: '',
        role: [1],
        submenu: [],
      },
      {
        path: '/elections/list',
        title: 'Elections',
        moduleName: 'elections',
        iconType: '',
        icon: '',
        class: 'navigation__sub',
        groupTitle: false,
        badge: '',
        badgeClass: '',
        role: [1],
        submenu: [],
      },
      {
        path: '/reports/transactions',
        title: 'Voting Transactions',
        moduleName: 'elections',
        iconType: '',
        icon: '',
        class: 'navigation__sub',
        groupTitle: false,
        badge: '',
        badgeClass: '',
        role: [1],
        submenu: [],
      },
      {
        path: '/reports/results',
        title: 'Elections Results',
        moduleName: 'elections',
        iconType: '',
        icon: '',
        class: 'navigation__sub',
        groupTitle: false,
        badge: '',
        badgeClass: '',
        role: [1],
        submenu: [],
      },

    ],
  },
  //Rooms
  {
    path: '',
    title: 'Voters',
    moduleName: 'voters',
    iconType: 'pe-7s-officers',
    icon: '',
    class: 'navigation__sub',
    groupTitle: false,
    badge: '',
    badgeClass: '',
    role: [1],
    submenu: [
      {
        path: '/voters/list',
        title: 'All Voters',
        moduleName: 'voters',
        iconType: '',
        icon: '',
        class: '',
        groupTitle: false,
        badge: '',
        badgeClass: '',
        role: [1],
        submenu: [],
      },
      {
        path: '/voters/add',
        title: 'New Voter',
        moduleName: 'voters',
        iconType: '',
        icon: '',
        class: 'navigation__sub',
        groupTitle: false,
        badge: '',
        badgeClass: '',
        role: [1],
        submenu: [],
      },
  

    ],
  },

  //Laundry
  {
    path: '/candidates/list',
    title: 'Candidates',
    moduleName: 'candidates',
    iconType: 'ti-user',
    icon: '',
    class: 'navigation__active',
    groupTitle: false,
    badge: '',
    badgeClass: '',
    role: [1],
    submenu: [
    ],
  },
  {
    path: '/settings/positions',
    title: 'Positions',
    moduleName: 'positions',
    iconType: 'ti-star',
    icon: '',
    class: 'navigation__active',
    groupTitle: false,
    badge: '',
    badgeClass: '',
    role: [1],
    submenu: [
    ],
  },
  {
    path: '/settings/departments',
    title: 'Departments',
    moduleName: 'departments',
    iconType:'pe-7s-portfolio',
    icon: '',
    class: 'navigation__active',
    groupTitle: false,
    badge: '',
    badgeClass: '',
    role: [1],
    submenu: [
    ],
  },

  //Reports 
  {
    path: '',
    title: 'Reports',
    moduleName: 'reports',
    iconType: 'flaticon-document-1',
    icon: '',
    class: 'navigation__sub',
    groupTitle: false,
    badge: '',
    badgeClass: '',
    role: [1],
    submenu: [
      {
        path: '/reports/transactions',
        title: 'Voting Transactions',
        moduleName: 'reports',
        iconType: '',
        icon: '',
        class: '',
        groupTitle: false,
        badge: '',
        badgeClass: '',
        role: [1],
        submenu: [],
      },
      {
        path: '/reports/results',
        title: 'Election results',
        moduleName: 'reports',
        iconType: '',
        icon: '',
        class: 'navigation__sub',
        groupTitle: false,
        badge: '',
        badgeClass: '',
        role: [1],
        submenu: [],
      },
      {
        path: '/reports/card-holders',
        title: 'Current holders',
        moduleName: 'reports',
        iconType: '',
        icon: '',
        class: 'navigation__sub',
        groupTitle: false,
        badge: '',
        badgeClass: '',
        role: [1],
        submenu: [],
      },
    ],
  },



  {
    path: '',
    title: 'Settings',
    moduleName: 'settings',
    iconType: 'ti-settings',
    icon: '',
    class: 'navigation__sub',
    groupTitle: false,
    badge: '',
    badgeClass: '',
    role: [1],
    submenu: [
      {
        path: '/settings/branches',
        title: 'Branches',
        moduleName: 'settings',
        iconType: '',
        icon: '',
        class: 'navigation__sub',
        groupTitle: false,
        badge: '',
        badgeClass: '',
        role: [1],
        submenu: [],
      },
      {
        path: '/settings/positions',
        title: 'Positions',
        moduleName: 'settings',
        iconType: '',
        icon: '',
        class: 'navigation__sub',
        groupTitle: false,
        badge: '',
        badgeClass: '',
        role: [1],
        submenu: [],
      },
      {
        path: '/settings/departments',
        title: 'Departments',
        moduleName: 'settings',
        iconType: '',
        icon: '',
        class: 'navigation__sub',
        groupTitle: false,
        badge: '',
        badgeClass: '',
        role: [1],
        submenu: [],
      },
      {
        path: '/settings/election-setup',
        title: 'Election Setup',
        moduleName: 'settings',
        iconType: '',
        icon: '',
        class: 'navigation__sub',
        groupTitle: false,
        badge: '',
        badgeClass: '',
        role: [1],
        submenu: [],
      },
      

    ],
  },
  

];

Component

import { Router, NavigationEnd } from '@angular/router';
import { DOCUMENT } from '@angular/common';
import {
  Component,
  Inject,
  ElementRef,
  OnInit,
  Renderer2,
  HostListener,
} from '@angular/core';
import { ROUTES } from './sidebar-items';
import { Role } from 'src/app/core/models/role';
import { AuthService } from 'src/app/core/service/auth.service';
@Component({
  selector: 'app-sidebar',
  templateUrl: './sidebar.component.html',
  styleUrls: ['./sidebar.component.css'],
})
export class SidebarComponent implements OnInit {
  dropdowns:any;
  public sidebarItems: any[];
  showMenu = 'dashboard';
  name:any='';
  showSubMenu = '';
  showSubSubMenu = '';
  public innerHeight: any;
  public bodyTag: any;
  listMaxHeight: string;
  listMaxWidth: string;
  userFullName: string;
  userImg: string;
  userType:any;
  level:any=''
  headerHeight = 60;
  currentRoute: string;
  constructor(
    @Inject(DOCUMENT) private document: Document,
    private renderer: Renderer2,
    public elementRef: ElementRef,
    private authService: AuthService,
    private router: Router
  ) {
    const body = this.elementRef.nativeElement.closest('body');
    this.router.events.subscribe((event) => {
      if (event instanceof NavigationEnd) {
        if (event.url.split('/')[1] === 'multilevel') {
          this.showMenu = event.url.split('/')[1];
        } else {
          this.showMenu = event.url.split('/').slice(-2)[0];
        }
        this.showSubMenu = event.url.split('/').slice(-2)[0];


        // close sidebar on mobile screen after menu select
        this.renderer.removeClass(this.document.body, 'overlay-open');
      }
    });
  }
  @HostListener('window:resize', ['$event'])
  windowResizecall(event) {
    this.setMenuHeight();
    this.checkStatuForResize(false);
  }
  @HostListener('document:mousedown', ['$event'])
  onGlobalClick(event): void {
    if (!this.elementRef.nativeElement.contains(event.target)) {
      this.renderer.removeClass(this.document.body, 'overlay-open');
    }
  }
  callMenuToggle(event: any, element: any) {
    if (element === this.showMenu) {
      this.showMenu = '0';
    } else {
      this.showMenu = element;
    }
    const hasClass = event.target.classList.contains('toggled');
    if (hasClass) {
      this.renderer.removeClass(event.target, 'toggled');
    } else {
      this.renderer.addClass(event.target, 'toggled');
    }
  }
  callSubMenuToggle(event: any, element: any) {
    if (element === this.showSubMenu) {
      this.showSubMenu = '0';
    } else {
      this.showSubMenu = element;
    }
  }
  ngOnInit() {

    if (this.authService.currentUserValue) {
      const userRole:any = this.authService.currentUserValue.role_id;
      this.level = this.authService.currentUserValue.role;
      this.userFullName = this.authService.currentUserValue.username;
      var name = this.userFullName
      let initials = name.match(/bw/g) || [];
      this.name = ((initials.shift() || '') + (initials.pop() || '')).toUpperCase();
//console.log(initials);
      this.userImg = this.authService.currentUserValue.img;

      this.sidebarItems = ROUTES.filter(
        (x) => x.role.indexOf(userRole) !== -1 || x.role.indexOf('All') !== -1
      );
      if (userRole === Role.Admin) {
        this.userType = Role.Admin;
      } else if (userRole === Role.Manager) {
        this.userType = Role.Manager;
      } else if (userRole === Role.User) {
        this.userType = Role.User;
      } else {
        this.userType = Role.Admin;
      }
    }

   // alert(JSON.stringify(this.userType))

    // this.sidebarItems = ROUTES.filter((sidebarItem) => sidebarItem);
    this.initLeftSidebar();
    this.bodyTag = this.document.body;
    
  }
  initLeftSidebar() {
    const _this = this;
    // Set menu height
    _this.setMenuHeight();
    _this.checkStatuForResize(true);
  }
  setMenuHeight() {
    this.innerHeight = window.innerHeight;
    const height = this.innerHeight - this.headerHeight;
    this.listMaxHeight = height + '';
    this.listMaxWidth = '500px';
  }
  isOpen() {
    return this.bodyTag.classList.contains('overlay-open');
  }
  checkStatuForResize(firstTime) {
    if (window.innerWidth < 1170) {
      this.renderer.addClass(this.document.body, 'ls-closed');
    } else {
      this.renderer.removeClass(this.document.body, 'ls-closed');
    }
  }
  mouseHover(e) {
    const body = this.elementRef.nativeElement.closest('body');
    if (body.classList.contains('submenu-closed')) {
      this.renderer.addClass(this.document.body, 'side-closed-hover');
      this.renderer.removeClass(this.document.body, 'submenu-closed');
    }
  }
  mouseOut(e) {
    const body = this.elementRef.nativeElement.closest('body');
    if (body.classList.contains('side-closed-hover')) {
      this.renderer.removeClass(this.document.body, 'side-closed-hover');
      this.renderer.addClass(this.document.body, 'submenu-closed');
    }
  }
  logout(){
  this.authService.logout()
  }
  redirectTo(currentUrl:any){
    //let currentUrl = this.router.url;

    this.router.navigate([currentUrl]).then(() => {
      window.location.reload();
    });

    // console.log(currentUrl);
    // this.router.navigateByUrl('/', {skipLocationChange: true}).then(() => {

    // });

    // this.router.navigateByUrl('/', {skipLocationChange: true}).then(()=>
    // this.router.navigate(['']));
 }
  togg(name:any) {
    //this.dropwdowns[name] = !this.dropwdowns[name];
}
}

sidebar-component.html

<div *ngIf="userType === 1">

<aside class="sidebar">
  <div class="scrollbar-inner">
    <div class="user">
      <div class="user__info" data-toggle="dropdown">
        <div class="avatar-char bg-warning text-black mr-3 font-weight-bold">
       <!--    {{name}} -->
        </div>
        <div>
          <div class="user__name">{{ userFullName }}</div>
          <div class="user__email">{{ level }}</div>
        </div>
      </div>

      <div class="dropdown-menu">
        <a class="dropdown-item" href="my-profile.html">View Profile</a>
        <a class="dropdown-item d-none" href="#">Settings</a>
        <a class="dropdown-item" href="landing-page.html" (click)="logout()"
          >Logout</a>
      </div>
    </div>

    <ul class="navigation">
      <li
        [class.active]="
          showMenu === sidebarItem.moduleName && sidebarItem.submenu.length != 0" *ngFor="let sidebarItem of sidebarItems"  [routerLinkActive]="sidebarItem.submenu.length != 0 ? '' : 'active'" class="navigation__sub">
        <a  style="color: white" (click)="sidebarItem.submenu.length === 0 ? redirectTo(sidebarItem.path):'' "
            *ngIf="!sidebarItem.groupTitle" ><i [ngClass]="[sidebarItem.iconType]" >{{ sidebarItem.icon }}</i>
          <span class="hide-menu" >{{ sidebarItem.title }}</span>
          <i class="zmdi zmdi-caret-down drop-down-icon" *ngIf="sidebarItem.submenu.length > 0"></i>
        </a>

        <ul class="" *ngIf="sidebarItem.submenu.length > 0">
          <li [ngClass]=" showSubMenu === sidebarSubItem.moduleName ? 'activeSub' : ''" *ngFor="let sidebarSubItem of sidebarItem.submenu"
            [routerLinkActive]="
              sidebarSubItem.submenu.length > 0 ? '' : 'active'
            "
          >
            <a (click)="redirectTo(sidebarSubItem.path)"  style="color: white" class="navigation__sub">{{ sidebarSubItem.title }}
            </a>

            <ul class="" *ngIf="sidebarSubItem.submenu.length > 0">
              <li
                *ngFor="let sidebarSubsubItem of sidebarSubItem.submenu"
                [ngClass]="
                  showSubSubMenu === sidebarSubsubItem.moduleName
                    ? 'activeSubSub'
                    : ''
                "
                [routerLinkActive]="
                  sidebarSubsubItem.submenu.length > 0 ? '' : 'active'
                "
              >
                <a
                  (click)="redirectTo(
                    sidebarSubsubItem.submenu.length > 0
                      ? null
                      : [sidebarSubsubItem.path])
                  "
                  [ngClass]="[sidebarSubsubItem.class]"
                >
                  {{ sidebarSubsubItem.title }}
                </a>
              </li>
            </ul>
          </li>
        </ul>
      </li>

      <li class="navigation__active mt-4" (click)="logout()">
        <a href="landing-page.html"><i class="zmdi zmdi-power"></i>Logout</a>
      </li>
    </ul>
  </div>
</aside>


</div>

Source: Angular Questions

Leave a Reply

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