1

I am using ngrx/router.

I have 4 pages. And two of them /admin/dashboard and /admin/management need admin access.

/home
/products

/admin/dashboard
/admin/management

I can click User and Admin to switch between user or admin views.

<li linkActive="active">
  <a linkTo="/home">User</a>
</li>
<li linkActive="active">
  <a linkTo="/admin/dashboard">Admin</a>
</li>

When I in /home and /products, I want User be active. Now only when in /home, it is active.

Similar, when I in /admin/dashboard and /admin/management, I want Admin be active. Now only when in /admin/dashboard, it is active.

How can I do that? Thanks

Hongbo Miao
  • 45,290
  • 60
  • 174
  • 267

1 Answers1

1

Thanks for the help from @brandonroberts.

The active link is based on the path, so /home and /products can't be active at the same time.

Unless you have links for /home and /products under the same li.

Then if one of those it active, it will add the active class.

So I end with this solution: using isAdminPage in AdminService inside of AdminGuard.

@Injectable()
export class AdminService {
  isAdminPage: boolean = false;
}


@Injectable()
export class AdminGuard implements Guard {
  constructor(
    private _router: Router,
    private _userService: UserService,
    private _adminService: AdminService) {}

  protectRoute(candidate: TraversalCandidate): Observable<boolean> {
    return this._userService.checkAdmin()
      .map(isAdmin => {
        if (!isAdmin) {
          this._router.replace('/home');
          return false;
        } else {
          this._adminService.isAdminPage = true;
          return true;
        }
      }).first();
  }
}

Then use _adminService.isAdminPage to detect:

<li class="nav-item" [class.active]="!_adminService.isAdminPage">
  <a class="nav-link" linkTo="/home">user</a>
</li>
<li class="nav-item" [class.active]="_adminService.isAdminPage">
  <a class="nav-link" linkTo="/admin/dashboard">admin</a>
</li>
Hongbo Miao
  • 45,290
  • 60
  • 174
  • 267