Welcome back! In this comprehensive tutorial, we'll delve deep into Angular Navigation, learning how to create both menus and side navigations. By the end of this lesson, you'll have practical, real-world examples to help you master these essential concepts. Let's get started!
Navigation in Angular refers to the process of moving between different pages or components of your application. This is typically done using menus and side navigations.
Navigation plays a crucial role in organizing your application and making it user-friendly. A well-structured navigation system allows users to easily find what they're looking for, enhancing their overall experience.
First, let's create a new Angular component for our menu.
ng generate component menuIn our menu.component.ts, we'll define an array of menu items.
import { Component } from '@angular/core';
@Component({
selector: 'app-menu',
templateUrl: './menu.component.html',
styleUrls: ['./menu.component.css']
})
export class MenuComponent {
menuItems = [
{ label: 'Home', path: '/' },
{ label: 'About', path: '/about' },
{ label: 'Contact', path: '/contact' }
];
}Now, let's create the menu in our menu.component.html.
<ul>
<li *ngFor="let menuItem of menuItems">
<a [routerLink]="menuItem.path">{{ menuItem.label }}</a>
</li>
</ul>Finally, let's add the menu to our app by updating the app.component.html.
<nav>
<app-menu></app-menu>
</nav>Just like before, let's create a new component for our side navigation.
ng generate component side-navIn our side-nav.component.ts, we'll define an array of menu items and a variable to manage the open state.
import { Component, EventEmitter, Input, Output } from '@angular/core';
@Component({
selector: 'app-side-nav',
templateUrl: './side-nav.component.html',
styleUrls: ['./side-nav.component.css']
})
export class SideNavComponent {
@Input() menuItems: any;
isOpen = false;
@Output() toggleSideNav = new EventEmitter();
toggle() {
this.isOpen = !this.isOpen;
this.toggleSideNav.emit({ isOpen: this.isOpen });
}
}Now, let's create the side navigation in our side-nav.component.html.
<div class="side-nav" [ngClass]="{ 'side-nav-open': isOpen }">
<ul>
<li *ngFor="let menuItem of menuItems">
<a [routerLink]="menuItem.path">{{ menuItem.label }}</a>
</li>
</ul>
<button (click)="toggle()">{{ isOpen ? 'Close' : 'Open' }} Side Navigation</button>
</div>To add the side navigation, we'll update the app.component.html like this:
<app-side-nav [menuItems]="menuItems"></app-side-nav>
<main>
<router-outlet></router-outlet>
</main>What does navigation in Angular refer to?
That's it for our Navigation tutorial! In the next lesson, we'll explore Angular routing and state management.
Stay tuned and happy coding! 💡📝🎯