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 ad
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();
}));
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!
In my case it happen because RouterModule was missed in the import.
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.
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.
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]
})