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
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.
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.
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
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With