RouterLink does not work

风格不统一 提交于 2019-11-27 09:56:01

问题


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?


回答1:


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.




回答2:


don't forget this to add this below in your template:

<router-outlet></router-outlet>



回答3:


Try changing the links as below:

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

Also, add the following in the header of index.html:

<base href="/">




回答4:


use it like this for mroe info read this topic

<a [routerLink]="['/about']">About this</a>



回答5:


The links are wrong, you have to do this:

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

You can read this tutorial




回答6:


I was using routerlink instead of routerLink.



来源:https://stackoverflow.com/questions/38832851/routerlink-does-not-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!