212

I have a mvc 5 project with a angular frontend . I wanted to add routing as described in this tutorial https://angular.io/guide/router. So in my _Layout.cshtml I added a

<base href="/">

and created my routing in my app.module. But when I run this I get the following error:

Error: Template parse errors:
    'router-outlet' is not a known element:
    1. If 'router-outlet' is an Angular component, then verify that it is part       of this module.
    2. If 'router-outlet' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA'   to the '@NgModule.schemas' of this component to suppress this message. ("
    <a routerLink="/dashboard">dashboard</a>
    </nav>
    [ERROR ->]<router-outlet></router-outlet>
     "): ng:///AppModule/AppComponent.html@5:0

In my app.component the line

<router-outlet></router-outlet>

gives an error telling me that Visual studio cannot resolve the tag 'router-outlet'. Any suggestions how I can fix this error? Am I missing a reference or a import or just overlooking something?

Below are my package.json ,app.component and app.module

package.json:

{
    "version": "1.0.0",
    "name": "app",
    "private": true,
    "scripts": {},
    "dependencies": {
    "@angular/common": "^4.2.2",
    "@angular/compiler": "^4.2.2",
    "@angular/core": "^4.2.2",
    "@angular/forms": "^4.2.2",
    "@angular/http": "^4.2.2",
    "@angular/platform-browser": "^4.2.2",
    "@angular/platform-browser-dynamic": "^4.2.2",
    "@angular/router": "^4.2.2",
    "@types/core-js": "^0.9.41",
    "angular-in-memory-web-api": "^0.3.2",
    "bootstrap": "^3.3.7",
    "core-js": "^2.4.1",
    "graceful-fs": "^4.0.0",
    "ie-shim": "^0.1.0",
    "minimatch": "^3.0.4",
    "reflect-metadata": "^0.1.10",
    "rxjs": "^5.0.1",
    "systemjs": "^0.20.12",
    "zone.js": "^0.8.12"
    },
    "devDependencies": {
    "gulp": "^3.9.1",
    "gulp-clean": "^0.3.2",
    "gulp-concat": "^2.6.1",
    "gulp-tsc": "^1.3.2",
    "gulp-typescript": "^3.1.7",
    "path": "^0.12.7",
    "typescript": "^2.3.3"
    }
}

app.module.ts:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { RouterModule, Routes } from '@angular/router';

import { AppComponent } from './app.component';
import {DashboardComponent} from "./dashboard/dashboard.component"    

const appRoutes: Routes = [
{
    path: '',
    redirectTo: '/dashboard',
    pathMatch: 'full',
    component: DashboardComponent
},  
{
    path: 'dashboard',
    component: DashboardComponent
}
];
@NgModule({
imports: [
    RouterModule.forRoot(appRoutes),
    BrowserModule,
    FormsModule               
],
exports: [RouterModule],
declarations: [
    AppComponent,  
    DashboardComponent      
],
bootstrap: [AppComponent]
})
export class AppModule {

}

app.component.ts:

import { Component } from '@angular/core';

@Component({
selector: 'my-app',
template: `
          <h1>{{title}}</h1>
          <nav>
          <a routerLink="/dashboard">dashboard</a>
          </nav>
          <router-outlet></router-outlet>
          `
})
export class AppComponent {
    title = 'app Loaded';

}
Philippe Fanaro
  • 6,148
  • 6
  • 38
  • 76
Molo
  • 2,143
  • 2
  • 13
  • 11

25 Answers25

193

Try this:

Import RouterModule into your app.module.ts

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

Add RouterModule into your imports []

like this:

 imports: [    RouterModule,  ]
Shubham Verma
  • 8,783
  • 6
  • 58
  • 79
  • 6
    Great, this solved my `'router-outlet' is not a known element` issue. for `Angular CLI version: 6.0.8` and `Angular version: 6.0.5` – Shams Jun 20 '18 at 06:55
  • 1
    Great, this also solved my ```'router-outlet' is not a known element``` issue. for ```Angular CLI version: 11.2.8``` and ```Angular version: 11.2.9``` – aghwotu Apr 16 '21 at 17:24
  • 4
    Unfortunately, this is already done, and yet the error persists. – O. R. Mapper Jul 19 '22 at 20:12
101

Try with:

@NgModule({
  imports: [
      BrowserModule,
      RouterModule.forRoot(appRoutes),
      FormsModule               
  ],
  declarations: [
      AppComponent,  
      DashboardComponent      
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

There is no need to configure the exports in AppModule, because AppModule wont be imported by other modules in your application.

Philippe Fanaro
  • 6,148
  • 6
  • 38
  • 76
Jota.Toledo
  • 27,293
  • 11
  • 59
  • 73
  • @Jota.Toledo I have created a separate Module file for routing where I have defined routes. Also I've BrowserModule, FormsModule in app.module imports and all three in routing-module file. But i'm still receiving this error. Any advise? – ninja_md Jan 21 '19 at 12:49
  • 1
    @ninja_md Did you add exports declaration to your routing-module file? Like below. `@NgModule({ imports: [ RouterModule.forRoot(appRoutes) ], exports: [ RouterModule ] })` I was getting same error and this fixed my problem. – Mihir Kagrana Aug 22 '19 at 02:19
  • I have add to import the RouterModule in the main.ts as well to make it work in Angular 15.2.x – felix at housecat Apr 02 '23 at 08:50
88

For those that already have RoutingModule imported in the parent module, sometimes the issue is caused by not adding the component with <router-outlet></router-outlet> in the module declarations.

main.component.html

<router-outlet></router-outlet>

main.module.ts

import { MainComponent } from './main.component';
import { SharedModule } from './../shared/shared.module';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { MainRoutingModule } from './main-routing.module';
import { RouterModule } from '@angular/router';


@NgModule({
  declarations: [
    MainComponent // <----- DON'T FORGET TO DECLARE THIS
  ],
  imports: [
    CommonModule,
    SharedModule,
    RouterModule,
    MainRoutingModule
  ]
})
export class MainModule { }

ezennnn
  • 1,239
  • 11
  • 13
60

If you are doing unit testing and get this error then Import RouterTestingModule into your app.component.spec.ts or inside your featured components' spec.ts:

import { RouterTestingModule } from '@angular/router/testing';

Add RouterTestingModule into your imports: [] like

describe('AppComponent', () => {

  beforeEach(async(() => {    
    TestBed.configureTestingModule({    
      imports: [    
        RouterTestingModule    
      ],
      declarations: [    
        AppComponent    
      ],    
    }).compileComponents();    
  }));
Philippe Fanaro
  • 6,148
  • 6
  • 38
  • 76
17

Assuming you are using Angular 6 with angular-cli and you have created a separate routing module which is responsible for routing activities - configure your routes in Routes array.Make sure that you are declaring RouterModule in exports array. Code would look like this:

@NgModule({
      imports: [
      RouterModule,
      RouterModule.forRoot(appRoutes)
     // other imports here
     ],
     exports: [RouterModule]
})
export class AppRoutingModule { }
Ashish Kamble
  • 2,555
  • 3
  • 21
  • 29
Manit
  • 1,087
  • 11
  • 17
  • I have created a separate Module file for routing as mentioned in your answer. Also I've BrowserModule, FormsModule in app.module imports and RouterModule in AppRouting file. But i'm still receiving this error. Can you help? – ninja_md Jan 21 '19 at 14:40
  • A little bit of code would help - routing module part and the app module part. – Manit Jan 22 '19 at 04:23
  • 1
    ninja_md Import your routing module in app.module imports array. second change would be that in routing module under @NgModule in exports array give the name of your module file that you have created fro routing. I hope this will solve your problem. – M.Sharma Jan 25 '19 at 07:23
  • Thank you for this! I was stuck on this for a while but did not add the bare `RouterModule` import (just the `.forRoot()` version). Adding it worked! – richid Aug 02 '22 at 03:13
13

Sometimes this error appears for no reason, which is solved by opening and closing your IDE.

12

It works for me, when i add following code in app.module.ts

@NgModule({
...,
   imports: [
     AppRoutingModule
    ],
...
})
Jigar Bhatt
  • 4,217
  • 2
  • 34
  • 42
7

Thank you Hero Editor example, where I found the correct definition:

When I generate app routing module:

ng generate module app-routing --flat --module=app

and update the app-routing.ts file to add:

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

Here are the full example:

import { NgModule }             from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { DashboardComponent }   from './dashboard/dashboard.component';
import { HeroesComponent }      from './heroes/heroes.component';
import { HeroDetailComponent }  from './hero-detail/hero-detail.component';

const routes: Routes = [
  { path: '', redirectTo: '/dashboard', pathMatch: 'full' },
  { path: 'dashboard', component: DashboardComponent },
  { path: 'detail/:id', component: HeroDetailComponent },
  { path: 'heroes', component: HeroesComponent }
];

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

and add AppRoutingModule into app.module.ts imports:

@NgModule({
  declarations: [
    AppComponent,
    ...
  ],
  imports: [
    BrowserModule,
    FormsModule,
    AppRoutingModule
  ],
  providers: [...],
  bootstrap: [AppComponent]
})
Kamlesh Kumar
  • 1,632
  • 2
  • 21
  • 31
5

Its just better to create a routing component that would handle all your routes! From the angular website documentation! That's good practice!

ng generate module app-routing --flat --module=app

The above CLI generates a routing module and adds to your app module, all you need to do from the generated component is to declare your routes, also don't forget to add this:

exports: [
    RouterModule
  ],

to your ng-module decorator as it doesn't come with the generated app-routing module by default!

Seyi Daniels
  • 190
  • 2
  • 8
4

I only had this problem in VS Code, running ng serve or ng build --prod did work fine.

What solved the issue for me, was simply disabling the Angular Language Service extension (angular.ng-template) and then re-enabling it.

officer
  • 2,080
  • 1
  • 20
  • 29
  • The problem was with Angular Language Service extension. I had to install a version exactly the same as the angular version in `package.json` – Lukas Coorek Mar 28 '23 at 10:51
4

There could be several reasons for this error:

First of all, don't forget to add AppRoutingModule to the app.module.ts file

app.module.ts:

imports: [AppRoutingModule]

If you created a new routing module, then you just need to import and export RouterModule in this routing module:

@NgModule({
  declarations: [],
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule],
})
export class NewRoutingModule {}

Then don't forget to add this NewRoutingModule to the main module file:

@NgModule({
  declarations: [NewComponent],               //--> Add NewComponent
  imports: [CommonModule, NewRoutingModule ]  //--> Add NewRoutingModule 
})
export class NewModule{}

And then this module to app.module.ts file:

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, AppRoutingModule, 
            BrowserAnimationsModule, 
            NewModule],       //--> Add NewModule
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule {}

For those who generate/create a new module and try to use <router-outlet> in this module without any new routing module. Don't forget to add RouterModule to the newly created module's imports and exports arrays.

newModule.module.ts:

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

@NgModule({
  declarations: [NewComponent],          //--> Add NewComponent
  imports: [CommonModule, RouterModule]  //--> Add RouterModule
  exports: [RouterModule],               //--> Add RouterModule
})
export class NewModule{}

and also don't forget to add the newly created module to app.module.ts imports array.

app.module.ts:

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, AppRoutingModule, 
            BrowserAnimationsModule, 
            NewModule],       //--> Add NewModule
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule {}
Omer
  • 8,194
  • 13
  • 74
  • 92
4

Make sure the following points to fix this issue:

  1. Import RouterModule module to the module.
  2. Add the component where into declarations array in the module.
  3. Make sure you imported the router module if you defined it explicitly.

See the following examples:

app.component.html

<router-outlet></router-outlet>

app-routing.module.ts

import { NgModule } from '@angular/core'; 
import { Routes, RouterModule } from '@angular/router';
import { AboutUsComponent } from './components/about-us/about-us.component';
import { ContactUsComponent } from './components/contact-us/contact-us.component';
import { IndexComponent } from './components/index/index.component';
const routes: Routes = [
{ path: '', redirectTo: 'index', pathMatch: 'full' }, 
{ path: 'index', component: IndexComponent },
{ path: 'about-us', component: AboutUsComponent },
{ path: 'contact-us', component: ContactUsComponent }
];
@NgModule({
imports: [
    RouterModule.forRoot(routes, { relativeLinkResolution: 'legacy' })
],
exports: [
    RouterModule
],
providers: []
})
export class AppRoutingModule { }

app.module.ts:

import { NgModule} from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { IndexComponent } from './components/index/index.component';
import { AboutUsComponent } from './components/about-us/about-us.component';
import { ContactUsComponent } from './components/contact-us/contact-us.component';
import { FormsModule } from '@angular/forms';
import { RouterModule } from '@angular/router';
import { CommonModule } from '@angular/common';

@NgModule({
  imports: [
CommonModule,
FormsModule,
RouterModule,
BrowserModule,
BrowserAnimationsModule, 
AppRoutingModule,
 ],
declarations: [AppComponent, IndexComponent, AboutUsComponent, ContactUsComponent],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule {}

It is working with me!!!

Mohammed Altaf
  • 151
  • 1
  • 5
3

In my case was a mistake on lazy loading. I was pointing to the routing module but it should be pointing to the module that own the routing module.

Wrong

const routes: Routes = [
  {
    path: 'Login',
    loadChildren: ()=> import('./login/login-routing.module.ts').then(m=> m.LoginRoutingModule)
  }
]

Right

const routes: Routes = [
  {
    path: 'Login',
    loadChildren: ()=> import('./login/login.module.ts').then(m=> m.LoginModule)
  }
]
Wagner Vieira
  • 351
  • 4
  • 16
2

I found a solution that worked for me. To test, I created a new project that worked fine, then gradually eliminated everything in app.component.html except for router-outlet line. THIS CONSISTENTLY cause this error. I was on VSCODE version 1.53.x so I upgraded to 1.54 (Feb 2021) and the problem disappeared.

Yogi Bear
  • 943
  • 2
  • 16
  • 32
2

If you manually created app-routing.module.ts or used a tool other than the CLI to do so, you'll need to import AppRoutingModule into app.module.ts and add it to the imports array of the NgModule. to create the app-routing.module.ts using the CLI run this:

ng generate module app-routing --flat --module=app
Dharman
  • 30,962
  • 25
  • 85
  • 135
Mounir
  • 155
  • 2
  • 12
1

In my case it happen because RouterModule was missed in the import.

yibela
  • 79
  • 3
1

you have juste to add "RouterModule" in "app.module" or "parent module", like that:

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

@NgModule({
  declarations: [
     ....
  ],
 imports: [
    ....
    RouterModule
 ]
})
export class LayoutsModule { }
Mounir bkr
  • 1,069
  • 6
  • 6
0

There are two ways. 1. if you want to implement app.module.ts file then:

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

const appRoutes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'user', component: UserComponent },
  { path: 'server', component: ServerComponent }
];

@NgModule({
  imports: [
    RouterModule.forRoot(appRoutes)
  ]
})
export class AppModule { }
  1. if you want to implement app-routing.module.ts (Separated Routing Module) file then:

//app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const appRoutes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'users', component: UsersComponent },
  { path: 'servers', component: ServersComponent }
];

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

//................................................................

//app.module.ts
import { AppRoutingModule } from './app-routing.module';

@NgModule({
  imports: [
    AppRoutingModule
  ]
})
export class AppModule { }
Shatu
  • 845
  • 6
  • 10
0
@NgModule({
  declarations: [
    SessionmagementComComponent, ***////Don't forgot to register main component for which html file you are using <router-outlet>...***
    LocalvssessionStorageComponent,
    SessionvslocallStorageComponent
  ],
  imports: [
    CommonModule,
    BrowserModule,
    SessionManagementStorageRoutingModule,
    RouterModule,
    AppRoutingModule
  ],
  exports: [
    LocalvssessionStorageComponent,
    SessionvslocallStorageComponent
  ]
})
export class SessionmagementModule { }
0

in my case, I accidently deleted AppComponent from @NgModule declarations in ap.modules.ts

Abdullah Nurum
  • 305
  • 2
  • 9
0

Sometimes this error might be shown if app.module.ts file has a error. in my case I was importing a component that did not exist anymore

Krishneel Singh
  • 324
  • 1
  • 8
  • 16
-1

This issue was with me also. Simple trick for it.

 @NgModule({
  imports: [
   .....       
  ],
 declarations: [
  ......
 ],

 providers: [...],
 bootstrap: [...]
 })

use it as in above order.first imports then declarations.It worked for me.

Susampath
  • 706
  • 10
  • 13
-1

I had the same problem more or less, I changed

 templateUrl: `<router-outlet></router-outlet>`, 

to

 template: `<router-outlet></router-outlet>`, 

By the way, plz notice that your component is exist on the declaration array of your module

Hamid
  • 761
  • 7
  • 18
-2

In your app.module.ts file

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

const appRoutes: Routes = [
{
    path: '',
    redirectTo: '/dashboard',
    pathMatch: 'full',
    component: DashboardComponent
},  
{
    path: 'dashboard',
    component: DashboardComponent
}
];

@NgModule({
imports: [
    BrowserModule,
    RouterModule.forRoot(appRoutes),
    FormsModule               
],
declarations: [
    AppComponent,  
    DashboardComponent      
],
bootstrap: [AppComponent]
})
export class AppModule {

}

Add this code. Happy Coding.

Vinayak Savale
  • 538
  • 6
  • 7
-3

Here is the Quick and Simple Solution if anyone is getting the error:

"'router-outlet' is not a known element" in angular project,

Then,

Just go to the "app.module.ts" file & add the following Line:

import { AppRoutingModule } from './app-routing.module';

And also 'AppRoutingModule' in imports.

4b0
  • 21,981
  • 30
  • 95
  • 142