Angular routerLink无法导航到相应的组件 [英] Angular routerLink does not navigate to the corresponding component

查看:63
本文介绍了Angular routerLink无法导航到相应的组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在angular2应用中的路由效果很好.但是我将基于制作一些routeLink:

这是我的路线:

  const路由:RouterConfig = [{path:'home',component:FormComponent},{path:'about',component:AboutComponent},{path:'**',组件:FormComponent}]; 

这是我创建的链接:

 < ul class ="nav navbar-nav item">< li>< routerLink ='/home'routerLinkActive ="active"> Home</a></li>< li>< a routerLink ="/关于" routerLinkActive =活动">关于此</a></li></ul> 

我希望当我单击它们时,它可以导航到相应的组件,但是它们什么也没执行?

解决方案

您在此处显示的代码绝对正确.

我怀疑您的问题是您没有将RouterModule(声明RouterLink的位置)导入使用此模板的模块中.

我遇到了类似的问题,由于该文档中未提及此步骤,因此花了一些时间来解决.

因此转到使用此模板声明组件的模块并添加:

 从'@ angular/router'导入{RouterModule}; 

然后将其添加到模块导入中,例如

  @NgModule({进口:[通用模块路由器模块],声明:[MyTemplatesComponent]})导出类MyTemplatesModule {} 

除了具有正确的导入语句外,您还需要一个显示该routerLink的位置,该位置位于< router-outlet></router-outlet> 元素中,因此还需要将其放置在HTML标记中的某个位置,以便路由器知道在何处显示该数据.

My routing in the angular2 apps works well. But I am going to make some routeLink based on this:

Here is my routing:

const routes: RouterConfig = [
    { path:'home' , component: FormComponent  },
    { path:'about', component: AboutComponent },
    { path:'**'   , component: FormComponent  }
];

And here are the links that I made:

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

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

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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆