Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

routerLink not working in Angular 6

I'm learning Angular 6.

I have designed my application structure in hierarchy form with following structure.

my_app
 |- src
    |- app
       |- layout
          |- admin-layout
             |- admin-layout.module.ts
             |- admin-layout.routing.ts
             |- admin-layout.component.html
       |- contacts
          |- contact-list
             |- contact-list.component.ts
             |- contact-list.component.html
          |- contacts.module.ts
       |- transaction
          |- amount-given
             |- amount-given-list
                |- amount-given-list.component.ts
                |- amount-given-list.component.html
             |- amount-given.module.ts
             |- amount-given.routing.ts
             |- amount-given.service.ts
          |- transaction.module.ts
          |- transaction.routing.ts
       |- app.module.ts
       |- app.component.html
       |- app-routing.module.ts

The source code and demo illustration can be found here: https://stackblitz.com/edit/angular-wcglvr

<a routerLink="/dashboard">Dashboard</a>

is working from /transaction/amount-given/amount-given-list/ but not from /contacts/contact-list.

Since source code is quite long and hierarchical, I have added demo illustration on stackblitz.

like image 244
Anuj TBE Avatar asked Aug 15 '18 13:08

Anuj TBE


People also ask

Should I use href or routerLink?

Always avoid href when using Angular or any other SPA. routerLink loads resources internal to Angular, and the page that loaded in the browser is never completely reloaded (and so app state is maintained.)

Can't bind to routerLink since it isn't a known property of DIV?

You need to add RouterModule to imports of every @NgModule() where components use any component or directive from (in this case routerLink and <router-outlet> . declarations: [] is to make components, directives, pipes, known inside the current module.

Can I use routerLink on button?

Can a button have routerLink Angular? After Angular v4 we can directly add a routerLink attribute on the anchor tag or button.

What does routerLink do in angular?

In Angular, RouterLink is a directive for navigating to a different route declaratively. Router. navigate and Router. navigateByURL are two methods available to the Router class to navigate imperatively in your component classes.


2 Answers

You have not imported RouterModule in ContactsModule.

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

@NgModule({
   imports: [
     RouterModule
   ],
like image 143
JB Nizet Avatar answered Sep 25 '22 00:09

JB Nizet


Add this in your contacts.module.ts

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

 @NgModule({
    imports: [
       RouterModule
     ],
like image 38
Sanjay Rajeev Avatar answered Sep 24 '22 00:09

Sanjay Rajeev