Angular routerLink does not navigate to the corresponding component
Asked Answered
L

19

191

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?

Lessee answered 8/8, 2016 at 15:14 Comment(6)
Can you please try [routerLink]='[/home']? What Angular2 version and router version are you using?Hindenburg
it doesn't work. are u sure with the place of your qutations?? I think i am using the last version of angular2, but i don't know how to check it. I generated it with ng new. and it should be updatedLessee
Sorry, should be [routerLink]="['/home']"Hindenburg
Maybe you forgot to add directives: [ROUTER_DIRECTIVES], to your component's metadata. Without that, Angular won't know to parse the routerLinks.Scrape
Possible duplicate of Angular2 Router link not workingMilitiaman
In my case, I was doing everything correctly but I've looped through li inside another li, and only outter li's routerlink was getting clicked.Regurgitate
I
500

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.

Importance answered 18/11, 2016 at 13:56 Comment(4)
I thought so and yes - you are absolutely right in my case too!Achates
Adding the Router module to my imports did the trick, thanks!Bladdernut
Nothing helps in my case. I have this problem in custom HttpErrorComponent which displays error information. So for instance if my page is not loaded because of Permission guard and just displays error 403 - the home button with routerLink on this page does not work (not clickable).Recall
had this issue with a lazy loaded module importing a shared module (was refactoring). this fixed it, thanksLiteracy
F
30

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

<router-outlet></router-outlet>
Floater answered 11/5, 2017 at 17:21 Comment(0)
S
16

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="/">

Stillbirth answered 18/11, 2016 at 21:44 Comment(0)
C
9

use it like this for mroe info read this topic

<a [routerLink]="['/about']">About this</a>
Chavira answered 8/8, 2016 at 15:15 Comment(3)
According to your link, his routerLink should work ;-)Hindenburg
This works for "@angular/router": "~3.4.0" . Cheers!Oswald
Yes, the bracket notation works (and is valid syntax with as specific purpose), but it's not a solution to this question.Militiaman
U
8

For anyone having this error after spliting modules check your routes, the following happened to me:

public-routing.module.ts:

const routes: Routes = [
    { path: '', component: HomeComponent },
    { path: '**', redirectTo: 'home' } // ← This was my mistake
    { path: 'home', component: HomeComponent },
    { path: 'privacy-policy', component: PrivacyPolicyComponent },
    { path: 'credits', component: CreditsComponent },
    { path: 'contact', component: ContactComponent },
    { path: 'news', component: NewsComponent },
    { path: 'presentation', component: PresentationComponent }
]

@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})
export class PublicRoutingModule { }

app-routing.module.ts:

const routes: Routes = [
];

@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})
export class AppRoutingModule { }

Move { path: '**', redirectTo: 'home' } to your AppRoutingModule:

public-routing.module.ts:

const routes: Routes = [
    { path: '', component: HomeComponent },
    { path: 'home', component: HomeComponent },
    { path: 'privacy-policy', component: PrivacyPolicyComponent },
    { path: 'credits', component: CreditsComponent },
    { path: 'contact', component: ContactComponent },
    { path: 'news', component: NewsComponent },
    { path: 'presentation', component: PresentationComponent }
]

@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})
export class PublicRoutingModule { }

app-routing.module.ts:

const routes: Routes = [
    { path: '**', redirectTo: 'home' }
];

@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})
export class AppRoutingModule { }
Uranology answered 31/12, 2019 at 10:59 Comment(2)
Please can you explain why?Diallage
I am no sured, but in your case may be the order of defined routes. The wildcards ("**") match all possible cases so the following routing definitions are ignored?Parrott
S
8

If you are using standalone components, make sure to add the RouterLink, RouterLinkActive, and RouterOutlet to the imports array of Component.

See docs for more info

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [CommonModule, RouterOutlet, RouterLink, RouterLinkActive],
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'routing-app';
}

Sweater answered 10/11, 2023 at 6:24 Comment(1)
This is the answer for Angular 17, thank you!Selfeffacing
I
6

I was using routerlink instead of routerLink.

Insured answered 29/9, 2019 at 3:30 Comment(1)
I made this mistake and this fixed it! I also have no idea why you were downvoted (perhaps because this could have been a comment instead or because it doesn't directly answer this specific question?). Would be nice if people who downvote it could provide a reason why.Inky
V
5

I'm aware this question is fairly old by now, and you've most likely fixed it by now, but I'd like to post here as reference for anyone that finds this post while troubleshooting this issue is that this sort of thing won't work if your Anchor tags are in the Index.html. It needs to be in one of the components

Voiture answered 9/12, 2019 at 5:14 Comment(0)
A
3

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

Alver answered 8/8, 2016 at 15:28 Comment(4)
Bracket notation serves a different purpose and does not solve this problem.Militiaman
this was it! <a [routerLink]="['/home']" routerLinkActive="active">Home</a> I was following the tutorial which had me put the routerLinkActive in the < li > tag. when I placed it in the < a tag it now works! Many thanks!!!! this is excellent!Fogle
BTW, I do have all the other tags/suggested elements in place already. Now this feature works (sort of). I have to follow the rest of the tutorial because I notice that when I select other rows, even though the value for the selected row is being passed (I see it in the url) only the first row is being rendered. But that will be another topic. Many thanks again for this great help.Fogle
I don't know why, but when I put Bracket, it worked for me, and I didn't import RouterModule in my app module..Stinson
P
1

There is also another case which suits this situation. If in your interceptor, you made it return non Boolean value, the end result is like that.

For example, I had tried to return obj && obj[key] stuff. After debugging for a while, then I realize I have to convert this to Boolean type manually like Boolean(obj && obj[key]) in order to let the clicking pass.

Pankhurst answered 27/1, 2020 at 14:28 Comment(0)
P
1

Following the working sample, I have figured out solution for the case of pure component:

  1. Declare component at app level
  2. Do not init in component
Prudential answered 6/4, 2020 at 23:37 Comment(0)
I
1

For not very sharp eyes like mine, I had href instead of routerLink, took me a few searches to figure that out #facepalm.

Intrust answered 14/5, 2020 at 0:28 Comment(0)
I
1

Most of the time problem is a spelling mistake in

<a [routerLink]="['/home']" routerLinkActive="active">Home</a>

Just check again for spelling.

Imperfect answered 23/8, 2020 at 13:36 Comment(0)
S
1

If you have your navbar inside a component and you declared your style active in that stylesheet, it won't work. In my case this was the problem.

my item of my navbar using angular material was:

<div class="nav-item">
        <a routerLink="/test" routerLinkActive="active">
          <mat-icon>monetization_on</mat-icon>My link
        </a>
<mat-divider class="nav-divider" [vertical]="true"></mat-divider>

so I put the style active in my style.scss in the root

a.active {
  color: white !important;
  mat-icon {
    color: white !important;
  }
}

I hope it helps you if the other solutions didn't.

Santosantonica answered 25/9, 2020 at 15:30 Comment(0)
L
1

In my case I had line-wrapper in my VS code and, apparently, there was no space between end of closing quote belonging to [routerLink] and next attribute. Line-wrapper split this in two lines so missing space went unnoticed.

Lunulate answered 27/11, 2020 at 12:54 Comment(0)
G
0

I was able to solve my problem by moving my navigation links from Index page to component (I actually had added template in index.html)

Goatherd answered 17/10, 2021 at 13:18 Comment(0)
C
0

Incase you're following https://angular.io/start/start-routing tutorial while using https://stackblitz.com/ as online IDE, opening/refreshing it in an new window fixed it.

Clabo answered 25/7, 2022 at 14:10 Comment(0)
C
0

Try adding the components you have created in the declarations array in the 'app.module.ts' or the respective module file so that your module knows that you have created these components. Also don't forget to import CommonModule and RouterModule.

import {AboutComponent} from './about.component';
import {FormComponent} from './form.component';

@NgModule({
  imports: [
    CommonModule,
    RouterModule
  ],
  declarations: [FormComponent, AboutComponent]
})
export class MyTemplatesModule { }
Cadet answered 14/12, 2022 at 4:3 Comment(0)
D
0

For anyone else having this issue and using routerLink on a font awesome icon, double check in dev tools whether the compiler converts the i element into an svg. If yes, you will have to wrap your i element inside another element, and bind to routerLink over there.

<a [routerLink]="'/some-route'">
  <i class="fas fa-arrow-left fa-2x cursor-pointer"></i>
</a>
Declivity answered 27/2 at 22:14 Comment(1)
Although your answer is likely helpful to someone, your answer is not related to the OP's question. Instead of keeping your answer here, please consider adding your answer to a more relevant post.Stealing

© 2022 - 2024 — McMap. All rights reserved.