When am I supposed to use router outlets? Obviously I have 1 in my app.component but what are some other use cases?
It seemed like a good idea to place 1 in my user component (user/:id)
to show a post list (user/:id/posts)
but then there seems to be no way to inject the user.posts
data into the outlet making this a bad idea in my opinion.
I'd love to hear some thoughts about this.
Edit: This post is specificly about how the router-outlet is unable to recieve data directly and therfor kinda defeats its own purpose in my opinion.
<router-outlet></router-outlet>
is essentially a directive that is exposed from @angular/router
. In our Routes
configuration, we specify the path
and the component
that is expected to be loaded when that path is reached.
But Angular doesn't know where it should inject that Component template. That's something that we tell Angular by specifying the <router-outlet></router-outlet>
.
Essentially, it acts as the container area for the Components that are supposed to be loaded via routing.
Where do you put it completely depends on the sort of routing config that you have in place.
In case of child routes, if you want to specify Components that would again be loaded based on routing, then you can specify a <router-outlet></router-outlet>
in that Parent Route Component as well.
Take a look at this Routes
config for eg:
const appRoutes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: 'blog', component: BlogComponent, canActivate: [ ActivateGuard ] },
{ path: 'messages', component: MessageListComponent, canDeactivate: [ DeactivateGuard ] },
{ path: 'parent', component: ParentComponent },
{ path: 'bd', component: BuiltInDirectivesComponent },
{ path: 'cd', component: CustomDirectivesComponent },
{ path: 'new-user', component: NewUserComponent },
{ path: 'new-user-reactive', component: NewUserReactiveComponent },
{
path: 'users',
component: UsersComponent,
children: [
{ path: ':userId', component: UserDetailsComponent },
{ path: '', component: PlaceholderComponent }
]
},
{ path: '**', redirectTo: '/home', pathMatch: 'full' }
];
Now say if I want to show a List of Users for the UsersComponent
and that too on the left. And on the right, I need to show the details of a selected user from the list.
In this case, there would be one <router-outlet></router-outlet>
in the AppComponent
Template. And then there would be another <router-outlet></router-outlet>
in the UsersComponent
Template. Hope it's clear now.