Angular Routing
What is Routing in Angular?
Routing it allows you to navigate between different views or pages in a single-page application.
Setting up Routing in Angular Applications
Import RouterModule: First, import the RouterModule and Routes from @angular/router in your root module (typically app.module.ts).
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
Define Routes: Next, define an array of route objects that map URL paths to components.
Each route object specifies a path and the component to display when that path is matched.
const routes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: 'contact', component: ContactComponent },
];
Configure Routes: Add the routes to the imports array of the @NgModule decorator, along with RouterModule.forRoot(routes).
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
Add Router Outlet: In the template of your root component (usually app.component.html), you should append a router-outlet element like this: <router-outlet></router-outlet>.
It is then that the browser will load the component matched the URL, identified by the current URL.
<router-outlet></router-outlet>
Route Parameters and Route Guards
Route Parameters: The route parameters are used to pass a data item to a component such as it is composing the URL.
You define route parameters by placing a colon (:Route name should be followed by `:` and parameter name should be placed in front of the parameter name in route path.
const routes: Routes = [
{ path: 'user/:id', component: UserComponent }
];
Accessing Route Parameters: You can access route parameters using the ActivatedRoute service in your component.
import { ActivatedRoute } from '@angular/router';
constructor(private route: ActivatedRoute) {
this.route.params.subscribe(params => {
this.userId = params['id'];
});
}
Route Guards: The lane guards provide you with the ability to prevent the route access of users who fail to meet some special requirements like authentication status or the roles of users.
Some examples of guards routes are CanActivate, CanActivateChild, CanDeactivate, CanivicLoad.
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router) {}
canActivate(): boolean {
if (loggedIn) {
return true;
} else {
this.router.navigate(['/login']);
return false;
}
}
}