In this tutorial, we will learn how to navigate between different components in an Angular application. Angular provides powerful routing and navigation capabilities that can be leveraged to create complex applications with multiple views and components.
By the end of this tutorial, you will be able to:
- Understand routing in Angular
- Use the routerLink and routerLinkActive directives
- Navigate between different components
Prerequisites:
- Basic knowledge of Angular
- Familiarity with TypeScript
- Angular CLI installed on your machine
Routing in Angular is a mechanism by which users can navigate through the application across different components. Angular provides the RouterModule
to manage navigation.
The routerLink
directive is used to link to routes. It's similar to the traditional 'href' in HTML, but works with Angular routes.
The routerLinkActive
directive is used to add a CSS class to the element when the linked route is active. This is commonly used to highlight the active route in a navigation menu.
Let's create a simple Angular application with two components: HomeComponent and AboutComponent.
// home.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-home',
template: `
<h1>Welcome to the Home Page!</h1>
`
})
export class HomeComponent { }
// about.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-about',
template: `
<h1>About Us</h1>
`
})
export class AboutComponent { }
Set up routes for the two components in the app-routing.module.ts
file.
// app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'about', component: AboutComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
Add navigation links in the AppComponent with routerLink and routerLinkActive directives.
<!-- app.component.html -->
<nav>
<a routerLink="/" routerLinkActive="active">Home</a>
<a routerLink="/about" routerLinkActive="active">About</a>
</nav>
<router-outlet></router-outlet>
In the code above, routerLink
sets the navigation path, and routerLinkActive
sets the CSS class to 'active' when the route is active.
In this tutorial, we covered the basics of navigation in Angular applications. We learned how to create routes and navigate between components using the routerLink and routerLinkActive directives.
For further learning, explore more advanced topics such as nested routes, route guards, and lazy loading.
Remember, the more you practice, the more you'll understand and be comfortable with Angular routing and navigation!