RouterLink不起作用 [英] RouterLink does not work

查看:215
本文介绍了RouterLink不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这是我的路线:

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>

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

解决方案

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

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

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

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

import { RouterModule } from '@angular/router';

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

@NgModule({
  imports: [
    CommonModule,
    RouterModule
  ],
  declarations: [MyTemplatesComponent]
})
export class MyTemplatesModule { }

除了具有正确的导入语句外,您还需要在<router-outlet></router-outlet>元素中显示该routerLink的位置,因此也需要将其放置在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 is 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 respected 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.

这篇关于RouterLink不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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