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:
app/app.routes.tsconst 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:
app/app.component.html<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:
app/aaaa/aaaa.component.tslet 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:
app/aaaa/aaaa.component.tsexport 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:
app/aaaa/aaaa.component.htmlmeaning: {{ value }}
Задание 1
Let the child component store the following array of objects:
typescript[
{
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.