I want to render 2 components (AppComponent and UserComponent) without having to render AppComponent at all times. Here's what my code looks like:
app.routing.module.ts
const routes: Routes = [
{
path: '', component: AppComponent
},
{
path: 'user', component: UserComponent
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
app.component.html
<div>
I'm in the app component
</div>
<router-outlet></router-outlet>
Now for some reason "I'm in the app component" text is rendered 2 times as you can see in the picture:
Now when I go to route '/user' I see this:
so my question is How can I only see "I'm in the app component" text when on on '/' route and when I'm on '/user' route only see "user works!"? Thanks a lot in advance!
CodePudding user response:
My answer is: Don't. Make an OtherComponent, then remove all but the <router-outlet>
tag from AppComponent.html.
Treat that AppComponent as the top level that everything flows through. Angular is very opinionated, and if you do things in a way that's not standard practice, Angular will act like it's meant to.
If the two branches should really be that separate, consider having separate apps.
CodePudding user response:
This is because default route ''
matches both ''
and 'user'
paths. Try setting pathMatch: 'full'
to the AppComponent
and it shouldn't render on other routes:
{
path: '',
component: AppComponent
pathMatch: 'full'
}
But more of an issue here is that the default route should be a separate component and your AppComponent
should be the one that holds the router-outlet
.
CodePudding user response:
You need to remove the AppComponent from your routing.
const routes: Routes = [
{
path: 'user', component: UserComponent
}
];
AppComponent renders by default. Here is the stackblitz for the same.
https://stackblitz.com/edit/angular-ivy-nivcaf?file=src/app/app.component.ts