angularselectorrouter-outlet

Child component is displayed under another child component


Child #1 Component: selector: 'app-home'

child #2 component: selector: 'app-plans'

child #1 html:

    <p>child 1 here</p>

child #2 html:

    <p>Child 2 here</p>

app.component.html:

<app-home></app-home>

app-routing.module.ts:

    const routes: Routes = [
    {path: 'plans', component: PlansComponent},
    {home: 'home', component: HomeComponent} 
    ]

in browser localhost:4200/plans displays: child 1 here child 2 here

if I change app.component.html to:

    <router-outlet></router-outlet>

localhost:4200/plans displays: child 2 here

What's wrong with using 'app-home' selector in app.component.html? why is it showing "child 1 here" in localhost:4200/plans? (i am expecting "child 2 here" only.)

shows results I expected, but I don't understand why doesn't work as I expected.


Solution

  • If you want to use the router strategy you need to insert the RouterOutlet directive in your main component like you did <router-outlet></router-outlet>. The RouterOutlet directive is a placeholder that angular fills dynamically with the appropriate content based on the active route.

    So if you have an active route like localhost:4200/plans and want to see only the component configured in the route definition PlansComponent, then you should just use <router-outlet></router-outlet> in your app component.

    With <app-home></app-home> in your app component you are just statically rendering the HomeComponent and nothing to do with your routing implementation.