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 {}
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
In order for the routerlink to work, you must import the Router to the component where you are working
Example
Import {Component} from '@ angular / core';
Import {Router} from '@ angular / router';
@Component ({
Selector: 'my-menu',
template:
<Div>
<a [routerLink]=["/comp11"]> Crisis Center </a>
<a <routerLink]=["/comp12"]> Heroes </a>
<a [routerLink]=["/comp21"]> Heroes </a>
<a <routerLink]=["/comp22"]> Heroes </a>
</ Div>
,})
Export class AppLayout{}
Thank you!
If this was a standalone component that was imported into a module then you could as well just add the RouterModule to the imports of your module. I for one like to have the module declarations in my own file so a solution here would be to have app-module.
import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';
import {RouterModule} from '@angular/router';
import {AppLayoutModule} from '...'; <--could also be a component
@NgModule({
declarations: [
AppComponent
],
imports: [
AppLayoutModule,
BrowserModule,
RouterModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
The only thing you must be sure of is that the RouterModule is imported into the module that uses the routerLink directive, either in the module file or the component file.
来源:https://stackoverflow.com/questions/40552619/angular2-router-link-not-working