What is routing in Angular and how is it implemented?
Routing in Angular is a mechanism for navigating between different views or pages in a single-page application (SPA). It allows you to define the different URL paths in your application and map them to the corresponding components that should be displayed for each URL.
Implementation of routing in Angular involves the following steps:
- Import the
RouterModule
from the@angular/router
library and include it in the imports array of the main module. - Define the routes in an array, where each element of the array is an object representing a single route. The object should contain a
path
property (representing the URL path), and acomponent
property (representing the component that should be displayed for the path). - Add the
<router-outlet>
component in your HTML template, which acts as a placeholder for the currently active component. - Use the
RouterLink
directive to create links in your HTML template that navigate to different routes when clicked.
Here is an example of how routing can be implemented in an Angular application:
import { RouterModule, Routes } from '@angular/router';
const routes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: '**', component: PageNotFoundComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
In this example, the routes are defined in the routes
constant, where each route is an object containing a path
and a component
property. The RouterModule.forRoot
method is used to initialize the router and pass in the routes
array. The <router-outlet>
component is placed in the HTML template, and the RouterLink
directive is used to create navigation links.