2
votes

I have just started learning routing in Angular and am trying to make a simple app that displays a home page with links to dashboard and contact pages.

app.component.ts

    import {Component} from '@angular/core'

    @Component({
      selector: 'my-app',
      template: `
        <router-outlet></router-outlet>
      `,
    })
    export class AppComponent {
      constructor() { }
    }

app.module.ts

    import {NgModule} from '@angular/core'
    import {BrowserModule} from '@angular/platform-browser'
    import {RouterModule} from '@angular/router'

    import { AppComponent } from './app.component'
    import {Home} from './home.component'
    import {Dashboard} from './dashboard.component'
    import {Contact} from './contact.component'

    @NgModule({
      imports: [ BrowserModule,
      RouterModule.forRoot([
        {path: 'home', component: Home},
        {path: 'dashboard', component: Dashboard},
        {path: 'contact', component: Contact},
        {path: '', redirectTo: '/home', pathMatch: 'full'}
        ])],
      declarations: [ AppComponent, Home, Dashboard, Contact ],
      bootstrap: [ AppComponent ]
    })
    export class AppModule {}

home.component.ts

    import {Component} from '@angular/core'

    @Component({
      template: `
        <h2>Home</h2>
        <nav>
          <a routerLink="/dashboard">Dashboard</a>
          <a routerLink="/contact">Contact</a>
        </nav>
        <router-outlet></router-outlet>
      `,
    })
    export class Home {
      constructor() { }
    }

The Dashboard and Contact pages should display below the nav bar, where router-outlet of Home component is defined. But instead, I think they are loading in the router-outlet defined in app.component.html. Why isn't the content of Dashboard/Contact component loading below the nav bar?

I tried searching through other questions but couldn't find answers relevant to this issue.

Plunkr- https://plnkr.co/edit/sjjJgHl5YHKsPVTGGDWs

1

1 Answers

1
votes

I think what you really want to do is something like below.

For the app.component:

import {Component} from '@angular/core'

@Component({
    selector: 'my-app',
    template: `
        <nav>
            <a routerLink="/home">Home</a>
            <a routerLink="/dashboard">Dashboard</a>
            <a routerLink="/contact">Contact</a>
        </nav>
        <router-outlet></router-outlet>
    `,
})
export class AppComponent {

}

And for the home.component:

import {Component} from '@angular/core'

@Component({
    template: `
        <h2>Home</h2>
    `,
})
export class Home {
    constructor() { }
}

Everything else is the same. All I did was move the nav into the app.component, added a home link into the nav, and removed the second router outlet from the home.component. Try it out.