RouterLink is not working in Angular 6

maneesha picture maneesha · Jun 15, 2018 · Viewed 11.5k times · Source

I was coding watching a Brad Traversy tutorial. and I did exactly as it is said. this is my 'app.module.ts'.

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

import { AppComponent } from './app.component';
import { NavbarComponent } from './components/navbar/navbar.component';
import { LoginComponent } from './components/login/login.component';
import { RegisterComponent } from './components/register/register.component';
import { HomeComponent } from './components/home/home.component';
import { ProfileComponent } from './components/profile/profile.component';
import { DashboardComponent } from './components/dashboard/dashboard.component';

const appRoutes: Routes = [
  {path:'', component: HomeComponent},
  {path:'register', component: RegisterComponent},
  {path:'login', component: LoginComponent},
  {path:'dashboard', component: DashboardComponent},
  {path:'profile', component: ProfileComponent}
] 
@NgModule({
  declarations: [
    AppComponent,
    NavbarComponent,
    LoginComponent,
    RegisterComponent,
    HomeComponent,
    ProfileComponent,
    DashboardComponent
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(appRoutes) // appRoutes: an object

  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

this is my navbar component

 <li><a class="nav-link" [routerLink] = "['/']" [routerLinkActive]=" 
['active']">Home</a></li>
 <li><a class="nav-link" [routerLink] = "['/login']" [routerLinkActive]=" 
['active']">Login</a></li>

I also added

<base href="/">

to the index.html file.

When I remove the RouterLink part the pages are working good.it displays the content inside the components when I give the path in the URL.

I checked in several questions. but I have done everything, I can't find an answer.

Answer

RamAnji picture RamAnji · Jun 15, 2018

write routerLinkActive as bellow..remove those brackets

 <li>
    <a class="nav-link" [routerLink] = "['/']" routerLinkActive="active">Home</a>
    </li>
    <li>
    <a class="nav-link" [routerLink] = "['/login']" routerLinkActive="active">Login</a> 
   </li>

official documentation :- https://angular.io/guide/router