Search code examples
angularangular2-routingangular2-template

Angular2 Router link not working


My router link works from the root component and the same link not working if I move the links to child component. The plunker code shows the working link and non working link. Thank you in advance. The below is the not working links.

//our root app component
import {Component} from '@angular/core'

@Component({
    selector: 'my-menu',
    template: `
    <div>
    <a routerLink="/comp11" routerLinkActive="active">Crisis Center</a> | 
    <a routerLink="/comp12" routerLinkActive="active">Heroes</a> | 
    <a routerLink="/comp21" routerLinkActive="active">Heroes</a> | 
    <a routerLink="/comp22" routerLinkActive="active">Heroes</a>
  </div>
`,
})
export class AppLayout {}

Plunker code with issue


Solution

  • You should import RouterModule in your AppLayoutModule so it looks as follows:

    import {NgModule} from '@angular/core'
    import {BrowserModule} from '@angular/platform-browser'
    import {AppLayout} from './layout.component';
    import {RouterModule} from '@angular/router';
    
    @NgModule({
        imports: [ BrowserModule, RouterModule ],
        declarations: [ AppLayout ],
        exports: [ AppLayout ]
    })
    
    export class AppLayoutModule {}
    

    Without it component didn't know what the routerLink is and do not compile it to correct href attributes.

    Updated Plunker here