Angular 10 Tutorial - Route Parameters
In this tutorial, we will learn about Route Parameters in Angular 10. Route parameters are parameters whose values are set dynamically in a page's URL. This allows a route to render the same component while passing that component the dynamic portion of the URL, so that it can change its data based on the parameter.
Creating a New Component
We can also pass a parameter with the route. So, let's see how we can pass a parameter in Angular 10. Before passing the parameter, just create a new component. Switch to the command prompt and type the command:
ng g c components/user
Configuring Routing
Now, switch to the project and open the app-routing.module.ts file and import the UserComponent:
import {UserComponent} from './components/user/user.component';
Now, add this UserComponent to the route:
const routes: Route = [
{
path:'user/:name',
component:UserComponent.
}
]
Accessing Route Parameters
Now, go to the user.component.ts file and import the following:
import { ActivatedRoute } from '@angular/router';
export class ContactComponent implements OnInit {
name='';
constructor(private route: ActivatedRoute) { }
ngOnInit(): void {
this.name = this.route.snapshot.params.name;
}
}
Displaying Route Parameters
Now, let's display this name to the user.component.html file. So, just open the user.component.html file and write:
<h1>{{name}}</h1>
Testing Route Parameters
Alright, now let's check it. Switch to the browser and go to the URL /user/Jennifer. Now, press enter. You can see the name. If you change the name, let's say Peter, you can see the name. So, in this way, you can add parameters in Angular 10 router.