Project 3: Admin Dashboard with Login, Guards and Lazy Routes
What We Build
- Login page and protected area
- Layout with sidebar, header and user menu
- Role-based menu (admin sees Users)
- Dashboard with stat cards and a chart
- Users table with search, sort and delete
- Everything lazy loaded
Folder Structure
text
src/app/
core/ auth.service.ts, auth.guard.ts, auth.interceptor.ts
layout/ shell.ts (sidebar + header + router-outlet)
features/
login/ login.ts
dashboard/ dashboard.ts
users/ users.ts, user.service.ts
app.routes.ts
app.config.ts
Reuse AuthService, authInterceptor, authGuard and roleGuard from the authentication lessons.
Step 1: Routes
typescript
export const routes: Routes = [
{ path: 'login', loadComponent: () => import('./features/login/login').then(m => m.Login) },
{
path: '',
canActivate: [authGuard],
loadComponent: () => import('./layout/shell').then(m => m.Shell),
children: [
{ path: '', pathMatch: 'full', redirectTo: 'dashboard' },
{ path: 'dashboard', loadComponent: () => import('./features/dashboard/dashboard').then(m => m.Dashboard) },
{
path: 'users',
canActivate: [roleGuard], data: { roles: ['admin'] },
loadComponent: () => import('./features/users/users').then(m => m.Users),
},
],
},
{ path: '**', redirectTo: '' },
];
Step 2: Shell Layout
typescript
@Component({
selector: 'app-shell',
imports: [RouterOutlet, RouterLink, RouterLinkActive],
changeDetection: ChangeDetectionStrategy.OnPush,
templateUrl: './shell.html',
styleUrl: './shell.css',
})
export class Shell {
auth = inject(AuthService);
collapsed = signal(false);
items = [
{ label: 'Dashboard', link: '/dashboard', icon: 'D' },
{ label: 'Users', link: '/users', icon: 'U', roles: ['admin'] as Role[] },
];
menu = computed(() => this.items.filter(i => !i.roles || this.auth.hasRole(...i.roles)));
}
html
<div class="layout" [class.collapsed]="collapsed()">
<aside>
<h2>Admin</h2>
<nav>
@for (i of menu(); track i.link) {
<a [routerLink]="i.link" routerLinkActive="active">{{ i.icon }} <span>{{ i.label }}</span></a>
}
</nav>
</aside>
<div class="main">
<header>
<button (click)="collapsed.set(!collapsed())" aria-label="Toggle menu">Menu</button>
<span>{{ auth.user()?.name }} ({{ auth.role() }})</span>
<button (click)="auth.logout()">Log out</button>
</header>
<main><router-outlet /></main>
</div>
</div>
css
.layout { display: grid; grid-template-columns: 220px 1fr; min-height: 100vh; }
.layout.collapsed { grid-template-columns: 64px 1fr; }
.collapsed span { display: none; }
aside { background: #1f2937; color: white; padding: 16px; }
aside a { display: block; color: #cbd5e1; padding: 10px; border-radius: 6px; text-decoration: none; }
aside a.active { background: #374151; color: white; }
header { display: flex; justify-content: space-between; align-items: center; padding: 12px 20px; border-bottom: 1px solid #e5e7eb; }
main { padding: 20px; }
Step 3: Dashboard Stats and Chart
typescript
export class Dashboard {
private http = inject(HttpClient);
stats = httpResource<{ users: number; orders: number; revenue: number }>(() => '/api/stats');
sales = httpResource<{ month: string; amount: number }[]>(() => '/api/sales');
max = computed(() => Math.max(1, ...(this.sales.value() ?? []).map(s => s.amount)));
}
html
<h1>Dashboard</h1>
<section class="cards">
@if (stats.value(); as s) {
<div class="card"><h3>Users</h3><p>{{ s.users | number }}</p></div>
<div class="card"><h3>Orders</h3><p>{{ s.orders | number }}</p></div>
<div class="card"><h3>Revenue</h3><p>{{ s.revenue | currency }}</p></div>
}
</section>
<h2>Monthly Sales</h2>
<div class="bars">
@for (s of sales.value() ?? []; track s.month) {
<div class="bar" [style.height.%]="(s.amount / max()) * 100" [title]="s.amount | currency">
<span>{{ s.month }}</span>
</div>
}
</div>
Real charts: For production use a library such as ngx-charts, Chart.js (with
ng2-charts) or ECharts, and load it with @defer so it does not slow the first page.
Step 4: Users Table with Search and Sort
typescript
export class Users {
private service = inject(UserService);
users = signal<User[]>([]);
term = signal('');
sortKey = signal<keyof User>('name');
asc = signal(true);
constructor() { this.service.getAll().subscribe(list => this.users.set(list)); }
rows = computed(() => {
const t = this.term().toLowerCase();
const key = this.sortKey();
const dir = this.asc() ? 1 : -1;
return this.users()
.filter(u => u.name.toLowerCase().includes(t) || u.email.toLowerCase().includes(t))
.sort((a, b) => String(a[key]).localeCompare(String(b[key])) * dir);
});
sortBy(key: keyof User) {
this.asc.set(this.sortKey() === key ? !this.asc() : true);
this.sortKey.set(key);
}
remove(u: User) {
if (!confirm(`Delete ${u.name}?`)) return;
this.service.delete(u.id).subscribe(() => this.users.update(list => list.filter(x => x.id !== u.id)));
}
}
html
<input placeholder="Search users" (input)="term.set($any($event.target).value)">
<table>
<thead>
<tr>
<th (click)="sortBy('name')">Name</th>
<th (click)="sortBy('email')">Email</th>
<th (click)="sortBy('role')">Role</th>
<th></th>
</tr>
</thead>
<tbody>
@for (u of rows(); track u.id) {
<tr>
<td>{{ u.name }}</td><td>{{ u.email }}</td><td>{{ u.role }}</td>
<td><button (click)="remove(u)">Delete</button></td>
</tr>
} @empty { <tr><td colspan="4">No users found.</td></tr> }
</tbody>
</table>
Testing Your Dashboard
- Open
/dashboardwhile logged out. You should be sent to/login - Log in as a normal user and open
/users. You should see Forbidden - Log in as admin and confirm the Users menu appears
- Check the Network tab: each feature file loads only when visited
Practice Ideas
- Add create and edit user forms with reactive forms
- Add server-side pagination
- Add dark mode with a signal and CSS variables
- Add unit tests for guards and services
Conclusion
This project combines login, guards, roles, a shell layout with lazy children, API-backed pages and a sortable table. It is a solid portfolio piece.
Quick Summary: Shell route with canActivate + role guard + lazy features + computed table.

