Angular2 Router link not working

≡放荡痞女 提交于 2019-11-30 18:28:26
Marcin

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.

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