No provider for ChildrenOutletContexts (injectionError)

I am getting the following error when using Angular CLI to generate a routing module for my application:

ERROR Error: No provider for ChildrenOutletContexts!
    at injectionError (core.es5.js:1169)
    at noProviderError (core.es5.js:1207)
    at ReflectiveInjector_.webpackJsonp.../../../core/@angular/core.es5.js.ReflectiveInjector_._throwOrNull (core.es5.js:2649)
    at ReflectiveInjector_.webpackJsonp.../../../core/@angular/core.es5.js.ReflectiveInjector_._getByKeyDefault (core.es5.js:2688)
    at ReflectiveInjector_.webpackJsonp.../../../core/@angular/core.es5.js.ReflectiveInjector_._getByKey (core.es5.js:2620)
    at ReflectiveInjector_.webpackJsonp.../../../core/@angular/core.es5.js.ReflectiveInjector_.get (core.es5.js:2489)
    at resolveNgModuleDep (core.es5.js:9481)
    at NgModuleRef_.webpackJsonp.../../../core/@angular/core.es5.js.NgModuleRef_.get (core.es5.js:10569)
    at resolveDep (core.es5.js:11072)
    at createClass (core.es5.js:10936)

I generated the routing module with Angular CLI like this:

ng generate module --routing App

This is the contents of the routing module:

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

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

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

And this is what I have in my app.component.html:

<div class="container" role="main">
    <router-outlet></router-outlet>
</div>

What can be the reason of this error?


To solve this problem change this line:

imports: [RouterModule.forChild(routes)],

to:

imports: [RouterModule.forRoot(routes)],

The error is caused because RouterModule.forChild() generates a module that contains the necessary directives and routes but doesn't include the routing service. That is what RouterModule.forRoot is for: it generates a module that contains the necessary directives, routes, and the routing service.

More information in Angular docs: Angular - Router Module.


This is usually happen to me when I didn't import the correct routing module.

For e.g: Inside AppModule I imported RouterModule from '@angular/router' by mistake instead of AppRoutingModule from './app-routing.module'

When i'm working with the Angular CLI I trust the compiler so I double check my self and in most cases it was my bad so when it comes to generating routing files along with the module i'm positive that Angular team are doing it good


imports: [RouterModule.forRoot(routes)]

Change this line in RoutingModuleclass