Angular2 Router link not working

浪子不回头ぞ 提交于 2019-11-30 03:19:15

问题


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


回答1:


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




回答2:


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!




回答3:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!