I want to display list of users when navigating to /users
and display an edit form for a specific user, when navigating to /users/123
.
I have an Angular Router configured as below and it works fine
const routes: Routes = [
{
path: 'users',
component: UsersListComponent,
},
{
path: 'users/:id',
component: EditUserComponent,
},
{
path: '**',
redirectTo: ''
}
];
But when I try to use children
route it doesn't work and /users/123
displays UsersListComponent
:
const routes: Routes = [
{
path: 'users',
component: UsersListComponent,
children: [
{
path: ':id',
component: EditUserComponent,
}
],
},
{
path: '**',
redirectTo: ''
}
];
What is the difference between these two approaches, why the 2nd one doesnt work and which one is correct?
CodePudding user response:
For the second example to work you'll need a <router-outlet></router-outlet>
inside the template of UsersListComponent
:
The first example works because both paths are on the same level and not in a parent/child relation.
which one is correct?
Usually in these kinds of scenarios you want to have them on the same level, because they're entirely different components, but if you wanted EditUserComponent
to be displayed inside of UsersListComponent
then you'd go for the second approach.
CodePudding user response:
It will work. You need a router-outlet tag in your User List component:
@Component({
selector: 'user-list',
template: `<h1>List</h1>
<div><a [routerLink]="['/users/999']">Click This User To Navigate</a></div>
<div>
<router-outlet></router-outlet>
</div>`,
})
export class UserListComponent {
}
@Component({
selector: 'edit-user',
template: '<h1>edit user</h1><p>{{id}}</p>',
})
export class EditUserComponent implements OnInit {
id: number;
constructor(private route: ActivatedRoute) {
}
ngOnInit(): void {
this.id = this.route.snapshot.paramMap.get("id");
}
}