A Beginner’s Guide to Angular: Modern Web Development Simplified Lesson – 4
8. Angular Routing and Navigation
Routing in Angular is a key feature that allows you to navigate between different views or pages in your application. In this lesson, we will cover how to set up routing, create routes, and navigate between them.
1. Introduction to Angular Routing
Angular provides a RouterModule that enables the configuration of routes within your application. This module helps in:
2. Setting Up Routing
To use routing in an Angular application, you first need to set up the RouterModule in your app. This can be done by importing it into your app module and defining routes.
Steps to Set Up Routing:
Example:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule, Routes } from '@angular/router';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
// Define routes
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'about', component: AboutComponent }
];
@NgModule({
declarations: [
AppComponent,
HomeComponent,
AboutComponent
],
imports: [
BrowserModule,
RouterModule.forRoot(routes) // Set up the routes
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
3. Creating Routes
领英推荐
For example:
4. Using the RouterLink Directive
To navigate between different routes, Angular provides the RouterLink directive. This directive allows you to link to specific routes within your template.
Example:
<nav>
<a routerLink="/">Home</a>
<a routerLink="/about">About</a>
</nav>
<!-- Routed components will be displayed here -->
<router-outlet></router-outlet>
The <router-outlet> directive is used to define the space where routed components will be displayed.
5. Navigating Programmatically
In addition to the RouterLink directive, you can navigate programmatically in your component’s TypeScript file by using the Router class.
Example:
import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-home',
template: `<button (click)="goToAbout()">Go to About</button>`
})
export class HomeComponent {
constructor(private router: Router) {}
goToAbout() {
this.router.navigate(['/about']);
}
}