In Angular, you can pass data through a router using parameters or query strings.
- Using Parameters: You can define parameters in the router configuration using the
:symbol. For example:
const routes: Routes = [
{ path: 'user/:id', component: UserComponent }
];
In this example, :id is the parameter that will be used to pass the user ID to the UserComponent. To navigate to this route and pass the parameter, you can use the router.navigate method:
this.router.navigate(['/user', userId]);
Here, userId is the value that you want to pass as the parameter.
In the UserComponent, you can retrieve the parameter using the ActivatedRoute service:
import { ActivatedRoute } from '@angular/router';
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.route.paramMap.subscribe(params => {
const userId = params.get('id');
// do something with userId
});
}
- Using Query Strings: You can also pass data through the router using query strings. To add query parameters to a URL, you can use the
queryParamsproperty of theNavigationExtrasobject:
const navigationExtras: NavigationExtras = {
queryParams: { 'param1': value1, 'param2': value2 }
};
this.router.navigate(['/user'], navigationExtras);
In this example, param1 and param2 are the query parameters that will be passed to the UserComponent. In the UserComponent, you can retrieve the query parameters using the ActivatedRoute service:
import { ActivatedRoute } from '@angular/router';
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.route.queryParams.subscribe(params => {
const param1 = params['param1'];
const param2 = params['param2'];
// do something with param1 and param2
});
}
These are the two ways in which you can pass data through a router in Angular.
