Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 Router link not working

My router link works from the root component and the same link not working if I move the links to child component. The plunker code shows the working link and non working link. Thank you in advance. The below is the not working links.

//our root app component
import {Component} from '@angular/core'

@Component({
    selector: 'my-menu',
    template: `
    <div>
    <a routerLink="/comp11" routerLinkActive="active">Crisis Center</a> | 
    <a routerLink="/comp12" routerLinkActive="active">Heroes</a> | 
    <a routerLink="/comp21" routerLinkActive="active">Heroes</a> | 
    <a routerLink="/comp22" routerLinkActive="active">Heroes</a>
  </div>
`,
})
export class AppLayout {}

Plunker code with issue

like image 529
balaG Avatar asked Nov 11 '16 16:11

balaG


People also ask

How to work router link in Angular?

To add links to one of the routes, use the routerLink directive in HTML. This directive accepts an array. The first parameter is the name of the route, and the second parameter is the parameters that you want to pass with the route.

Can we use router link in button?

Using Router linksAfter Angular v4 we can directly add a routerLink attribute on the anchor tag or button. Consider the following template, where routerLink attribute added to the anchor tag. The routerLink directive on the anchor tags give the router control over those elements.


2 Answers

You should import RouterModule in your AppLayoutModule so it looks as follows:

import {NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import {AppLayout} from './layout.component';
import {RouterModule} from '@angular/router';

@NgModule({
    imports: [ BrowserModule, RouterModule ],
    declarations: [ AppLayout ],
    exports: [ AppLayout ]
})

export class AppLayoutModule {}

Without it component didn't know what the routerLink is and do not compile it to correct href attributes.

Updated Plunker here

like image 180
Marcin Avatar answered Oct 04 '22 03:10

Marcin


In order for the routerlink to work, you must import the Router to the component where you are working

Example

Import {Component} from '@ angular / core';
Import {Router} from '@ angular / router';

@Component ({
Selector: 'my-menu',
template:
<Div>
<a [routerLink]=["/comp11"]> Crisis Center </a>
<a <routerLink]=["/comp12"]> Heroes </a>
<a [routerLink]=["/comp21"]> Heroes </a>
<a <routerLink]=["/comp22"]> Heroes </a>
</ Div>
,}) 
Export class AppLayout{}

Thank you!

like image 30
Daniel Garcia Avatar answered Oct 04 '22 02:10

Daniel Garcia