Using Route Parameters in a Component in Angular
Let's now see how we can use route parameters inside a component class.
Let's say we have the following route with parameters:
const routes: Routes = [
{ path: 'aaaa/:id', component: AaaaComponent },
{ path: 'bbbb', component: BbbbComponent },
];
Let's say we have links to go to this component with different parameters:
<nav>
<a
routerLink="/aaaa/1"
routerLinkActive="active"
>
1
</a>
<a
routerLink="/aaaa/2"
routerLinkActive="active"
>
2
</a>
<a
routerLink="/aaaa/3"
routerLinkActive="active"
>
3
</a>
</nav>
Let the child component contain the following array:
let arr: string = [
'a', 'b', 'c', 'd', 'e'
];
export class AaaaComponent {
}
Let's get the corresponding array element depending on the value of the route parameter:
export class AaaaComponent {
constructor(private activateRoute: ActivatedRoute) {
let params = activateRoute.snapshot.params;
let id = params['id'];
this.value = arr[id];
}
}
Let's display the resulting element in the view:
meaning: {{ value }}
Let the child component store the following array of objects:
[
{
name: 'user1',
surn: 'surn1',
},
{
name: 'user2',
surn: 'surn2',
},
{
name: 'user3',
surn: 'surn3',
},
]
Make a route with a parameter. Let the data of one of the users be displayed in the view depending on the parameter value.