[angular] Can't bind to 'routerLink' since it isn't a known property

Recently, I have started playing with angular 2. It's awesome so far. So, i have started a demo personal project for the sake of learning using angular-cli.

With the basic routing setup, I now want to navigate to some routes from header, but since my header is a parent to the router-outlet, I receive this error.

app.component.html

<app-header></app-header> // Trying to navigate from this component
    <router-outlet></router-outlet>
<app-footer></app-footer>

header.component.html

<a [routerLink]="['/signin']">Sign in</a>

Now I understand partially I guess that since that component is a wrapper around router-outlet it would not be possible this way to access router. So, is there a possibility to access navigation from outside for a scenario like this?

I would be really happy to add any more information if needed. Thank you in advance.

Update

1- My package.json already has the stable @angular/router 3.3.1 version. 2- In my main app module, I have imported the routing-module. Please see below.

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AlertModule  } from 'ng2-bootstrap';
import { LayoutModule } from './layout/layout.module';
import { UsersModule } from './users/users.module';
import { AppRoutingModule } from  './app-routing.module';
import { AppComponent } from './app.component';
import { PageNotFoundComponent } from './shared/components/not-found.component';

@NgModule({
  declarations: [
    AppComponent,
    PageNotFoundComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    AlertModule.forRoot(),
    LayoutModule,
    UsersModule,
    AppRoutingModule  --> This is the routing module. 
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { SigninComponent } from './users/signin/signin.component';
import { PageNotFoundComponent } from './shared/components/not-found.component';

const routes: Routes = [
{ path: '**', component: PageNotFoundComponent }
];

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

export class AppRoutingModule {}

The route I am trying to access is delegated from another module that is the UsersModule

user-routing.module.ts

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { SigninComponent } from './signin/signin.component';

const usersRoutes: Routes = [
  { path: 'signin',  component: SigninComponent }
];
@NgModule({
  imports: [
    RouterModule.forChild(usersRoutes)
  ],
  exports: [
    RouterModule
  ]
})

export class UsersRoutingModule { }

While I am trying to navigate from a component that is part of the Layout module, but has no notion of the router module. Is that what is causing the error.

Layout.module.ts

import { NgModule } from '@angular/core';
import { HeaderComponent } from './header/header.component';
import { FooterComponent } from './footer/footer.component';

@NgModule({
  declarations: [HeaderComponent, FooterComponent],
  exports: [HeaderComponent, FooterComponent]
})
export class LayoutModule{}

I am trying to navigate from the HeaderComponent. I would be happy to provide more information if needed.

This question is related to angular typescript angular2-routing

The answer is


I am running tests for my Angular app and encountered error Can't bind to 'routerLink' since it isn't a known property of 'a' as well.

I thought it might be useful to show my Angular dependencies:

    "@angular/animations": "^8.2.14",
    "@angular/common": "^8.2.14",
    "@angular/compiler": "^8.2.14",
    "@angular/core": "^8.2.14",
    "@angular/forms": "^8.2.14",
    "@angular/router": "^8.2.14",

The issue was in my spec file. I compared to another similar component spec file and found that I was missing RouterTestingModule in imports, e.g.

    TestBed.configureTestingModule({
      declarations: [
        ...
      ],
      imports: [ReactiveFormsModule, HttpClientTestingModule, RouterTestingModule],
      providers: [...]
    });
  });

You need to add RouterMoudle into imports sections of the module containing the Header component


When nothing else works when it should work, restart ng serve. It's sad to find this kind of bugs.


I totally chose another way for this method.

app.component.ts

import { Router } from '@angular/router';
export class AppComponent {

   constructor(
        private router: Router,
    ) {}

    routerComment() {
        this.router.navigateByUrl('/marketing/social/comment');
    }
}

app.component.html

<button (click)="routerComment()">Router Link </button>

In the current component's module import RouterModule.

Like:-

import {RouterModule} from '@angular/router';
@NgModule({
   declarations:[YourComponents],
   imports:[RouterModule]

...

It helped me.


I was getting this error, even though I have exported RouterModule from app-routing.module and imported app-routingModule in Root module(app module).

Then I identified, I've imported component in Routing Module only.

Declaring the component in my Root module(App Module) solves the problem.

declarations: [
AppComponent,
NavBarComponent,
HomeComponent,
LoginComponent],

You are missing either the inclusion of the route package, or including the router module in your main app module.

Make sure your package.json has this:

"@angular/router": "^3.3.1"

Then in your app.module import the router and configure the routes:

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

imports: [
        RouterModule.forRoot([
            {path: '', component: DashboardComponent},
            {path: 'dashboard', component: DashboardComponent}
        ])
    ],

Update:

Move the AppRoutingModule to be first in the imports:

imports: [
    AppRoutingModule.
    BrowserModule,
    FormsModule,
    HttpModule,
    AlertModule.forRoot(), // What is this?
    LayoutModule,
    UsersModule
  ],

In my case I just need to import my newly created component to RouterModule

{path: 'newPath', component: newComponent}

Then in your app.module import the router and configure the routes:

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

imports: [
        RouterModule.forRoot([
            {path: '', component: DashboardComponent},
            {path: 'dashboard', component: DashboardComponent},
            {path: 'newPath', component: newComponent}
        ])
    ],

Hope this helps to some one !!!


I'll add another case where I was getting the same error but just being a dummy. I had added [routerLinkActiveOptions]="{exact: true}" without yet adding routerLinkActive="active".

My incorrect code was

<a class="nav-link active" routerLink="/dashboard" [routerLinkActiveOptions]="{exact: true}">
  Home
</a>

when it should have been

<a class="nav-link active" routerLink="/dashboard" routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}">
  Home
</a>

Without having routerLinkActive, you can't have routerLinkActiveOptions.


This problem is because you did not import the module

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

And you must declare this modulce in the import section

   imports:[RouterModule]

Examples related to angular

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class error TS1086: An accessor cannot be declared in an ambient context in Angular 9 TS1086: An accessor cannot be declared in ambient context @angular/material/index.d.ts' is not a module Why powershell does not run Angular commands? error: This is probably not a problem with npm. There is likely additional logging output above Angular @ViewChild() error: Expected 2 arguments, but got 1 Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class' Access blocked by CORS policy: Response to preflight request doesn't pass access control check origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

Examples related to typescript

TS1086: An accessor cannot be declared in ambient context Element implicitly has an 'any' type because expression of type 'string' can't be used to index Angular @ViewChild() error: Expected 2 arguments, but got 1 Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; } Understanding esModuleInterop in tsconfig file How can I solve the error 'TS2532: Object is possibly 'undefined'? Typescript: Type 'string | undefined' is not assignable to type 'string' Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740] Can't perform a React state update on an unmounted component TypeScript and React - children type?

Examples related to angular2-routing

'router-outlet' is not a known element How to reload page the page with pagination in Angular 2? Error: Cannot match any routes. URL Segment: - Angular 2 Can't bind to 'routerLink' since it isn't a known property Passing data into "router-outlet" child components How to determine previous page URL in Angular? How to get parameter on Angular2 route in Angular way? Angular 2 Scroll to top on Route Change Angular routerLink does not navigate to the corresponding component Angular 2 router.navigate