Introduction to Angular Routing
Angular Routing allows you to build single-page applications with multiple views and navigation. This tutorial covers the basics of setting up and using Angular Router effectively in your Angular applications.
Setting Up Angular Router
To set up Angular Router, you need to import the necessary modules and define your application routes:
// app.module.ts
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';
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'about', component: AboutComponent }
];
@NgModule({
declarations: [AppComponent, HomeComponent, AboutComponent],
imports: [BrowserModule, RouterModule.forRoot(routes)],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
// home.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-home',
template: 'Home Component
',
})
export class HomeComponent { }
// about.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-about',
template: 'About Component
',
})
export class AboutComponent { }
// app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent { }
// app.component.html
Using RouterLink and RouterOutlet
Use the routerLink
directive to define navigation links and the router-outlet
directive to display the routed components:
// app.component.html
Handling Navigation
To handle navigation in Angular, you can use the Router
service. Here’s an example of navigating programmatically:
// app.component.ts
import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private router: Router) {}
goToAbout() {
this.router.navigate(['/about']);
}
}
// app.component.html
Key Points
- Angular Routing allows you to build single-page applications with multiple views and navigation.
- Define your application routes using the
RouterModule
andRoutes
array. - Use the
routerLink
directive to define navigation links and therouter-outlet
directive to display routed components. - Use the
Router
service to navigate programmatically.
Conclusion
Angular Routing is a powerful feature that allows you to build single-page applications with multiple views and smooth navigation. By understanding and using Angular Router effectively, you can create dynamic and user-friendly applications. Happy coding!