In Angular, you can pass route data to a component using the Angular Router. Route data can be useful when you want to pass additional information to a component based on the route it's associated with.
In this post, we will learn about- Passing Route Data as
Component Input, one of the features of Angular.
// app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { MyComponent } from './my-component.component';
const routes: Routes = [
{
path: 'example',
component:
MyComponent,
data: { id: '1',
name: 'anil singh' } // Route data
},
// Other routes...
];
@NgModule({
imports:
[RouterModule.forRoot(routes)],
exports:
[RouterModule]
})
export class AppRoutingModule {}
In the example above, the data property is used to attach additional information to the route. In this case, it includes two properties: id with the value '1' and name with the value 'anil singh'.
// my-component.component.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector:
'app-my-component',
template: `
<div>
<h2>My
Component</h2>
<p>ID: {{
routeData.id }}</p>
<p>Name:
{{ routeData.name }}</p>
</div>
`
})
export class MyComponent implements OnInit {
routeData: any; //
Define a property to hold the route data
constructor(private
route: ActivatedRoute) {}
ngOnInit(): void {
// Access the
route data
this.route.data.subscribe(data => {
this.routeData =
data;
});
}
}
In the MyComponent component, you can inject the ActivatedRoute service to access the route data. The ngOnInit lifecycle hook is a good place to do this. By subscribing to the data observable, you can get the route data and use it in your component.
Now, when you navigate to the 'example' route, the MyComponent will display the values of Id and Name from the route data.
Result,
My Component
1.
Id: 1
2.
Name: anil singh
On the My Component, you can read the route parameter using the ActivatedRoute service,
private route = inject(ActivatedRoute);
ngOnInit(): void {
this.route.params.subscribe(data =>{
console.log(data['id']);
})
}
private route = inject (ActivatedRoute);
ngOnInit(): void {
this.route.queryParams.subscribe(data=>{
console.log(data['name']);
})
}
On navigating to http://localhost:4200/id/1?name=anil singh you can see the route parameter and query parameter