Angular2路由器链接无法正常工作

时间:2016-11-11 16:50:48

标签: angular angular2-routing angular2-template

如果我将链接移动到子组件,我的路由器链接将从根组件和相同的链接工作。 plunker代码显示工作链接和非工作链接。先感谢您。以下是不起作用的链接。

//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

3 个答案:

答案 0 :(得分:24)

您应该在AppLayoutModule中导入RouterModule,使其如下所示:

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 {}

如果没有它,组件就不知道routerLink是什么,也不会编译它来纠正href属性。

更新了Plunker here

答案 1 :(得分:1)

要使routerlink工作,您必须将路由器导入到您正在使用的组件

实施例

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{}

谢谢!

答案 2 :(得分:0)

如果这是一个导入模块的独立组件,那么您也可以将RouterModule添加到模块的导入中。我喜欢在我自己的文件中使用模块声明,因此这里的解决方案是使用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 {}

您必须确定的唯一事情是将RouterModule导入到使用routerLink指令的模块中,无论是在模块文件还是组件文件中。

相关问题