Angular2路由器链接不工作
问题描述:
如果我将链接移动到子组件,我的路由器链接从根组件和相同的链接不工作。 plunker代码显示工作链接和非工作链接。先谢谢你。以下是不工作的链接。Angular2路由器链接不工作
//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 {}
答
你应该在你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
答
为了使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{}
谢谢!
答
如果这是被导入一个模块,那么你可能也只是RouterModule添加到您的模块的进口独立组件。我喜欢在我自己的文件中拥有模块声明,因此这里的解决方案应该是具有应用程序模块。
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指令,无论是在模块文件或组件文件的模块。
嗨@Marcin,我很好奇,RouterModule是在AppRoutingModule中导入的,它对所有其他功能模块都是可见的,所以我错了吗? – Howard
@Howard,它不可见,因为模块不会继承对其他模块的组件,提供者等的访问。因此,AppModule导入的内容对AppLayoutModule不可访问/可见。 – Marcin
嗨@Marcin,谢谢你的回答。这使我困惑不已。因此,如果我有第三方模块A声明几个'组件',你的意思是我不能在任何其他功能模块中使用它们,如果我只是'将这个模块A'导入到根模块?这有点奇怪,如果这个模块A需要'forRoot'配置呢?我是否必须在每个功能模块中“导入”和“配置”它取决于它? – Howard