Angular routerLink 没有导航到对应的组件 [英] Angular routerLink does not navigate to the corresponding component
问题描述
我在 angular2 应用程序中的路由运行良好.但我将根据 this 制作一些 routeLink:
My routing in the angular2 apps works well. But I am going to make some routeLink based on this:
这是我的路线:
const routes: RouterConfig = [
{ path:'home' , component: FormComponent },
{ path:'about', component: AboutComponent },
{ path:'**' , component: FormComponent }
];
这是我制作的链接:
<ul class="nav navbar-nav item">
<li>
<a routerLink='/home' routerLinkActive="active">Home</a>
</li>
<li>
<a routerLink='/about' routerLinkActive="active">About this</a>
</li>
</ul>
我希望,当我点击它们时,它会导航到相应的组件,但它们不执行任何操作?
I expect that, when I click on them it navigates to the corresponding component, but they do not perform anything?
推荐答案
您在此处显示的代码绝对正确.
The code you are showing there is absolutely correct.
我怀疑您的问题是您没有将 RouterModule(即 RouterLink 声明的地方)导入到使用此模板的模块中.
I suspect that your problem is that you are not importing RouterModule (which is where RouterLink is declared) into the module which uses this template.
我遇到了类似的问题,我花了一些时间来解决,因为文档中没有提到这一步.
I had a similar problem and it took me some time to solve as this step is not mentioned in the documentation.
因此转到使用此模板声明组件的模块并添加:
So go to the module that declares the component with this template and add:
import { RouterModule } from '@angular/router';
然后将其添加到您的模块导入中,例如
then add it to your modules imports e.g.
@NgModule({
imports: [
CommonModule,
RouterModule
],
declarations: [MyTemplatesComponent]
})
export class MyTemplatesModule { }
除了拥有正确的导入语句外,您还需要一个位置来显示该 routerLink,它位于
元素中,因此还需要将其放置在 HTML 标记中的某个位置,以便路由器知道在哪里显示该数据.
Along with having the correct import statements, you'll also need a place for that routerLink to be shown, which is in the <router-outlet></router-outlet>
element, so that also needs to be placed somewhere in your HTML markup so the router knows where to display that data.
这篇关于Angular routerLink 没有导航到对应的组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!