Search code examples
angularangular4-router

Angular 4 not loading component


I'm trying to use Angular Routes in Angular 4 app, but the app is not able to load the component matching the requested route:

Here is app-routing.module.ts:

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

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

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

app.module.ts looks like this:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { AppRoutingModule } from './app-routing.module';

@NgModule({
  declarations: [
    AppComponent,
    DashboardComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
  ],
  providers: [ ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }

app.component.html:

<h1>
    Welcome to {{title}}!
</h1>
<router-outlet></router-outlet>

My dashboard.component.html :

<p>dashboard works!</p>

I'm trying to figure out whats wrong, also looked at the Angular 4 Routing tutorial. Please help.


Solution

  • I found the solution after some troubleshooting, and found the answer on this link. Basically, in app.module.ts, we just have to add this import statement for importing APP_BASE_HREF token:

    import { APP_BASE_HREF } from '@angular/common';
    

    And add the APP_BASE_HREF to providers array:

    providers: [ {provide: APP_BASE_HREF, useValue: '/' }],
    

    Another solution according to the Angular documentation is to simply add <base href="/"> as the first child of <head> tag.