angularangular-routerlink

Problems with angular-routerLink


I have two problems with routerLink. The first problem is routerLink is unclickable. I mean literally. Here is my code:

<div class="collapse navbar-collapse" style="margin-left: 50%">
          <ul class="navbar-nav ml-auto">
            <li class="nav-item">
              <a class="nav-link" href="/login">Log in</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" routerLink="/register">Register</a>
            </li>
          </ul>
</div>

When I use href, everything works without a problem. I imported Routes and RouterModule in app.module.ts

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

Then I created paths:

const appRoutes: Routes = [
  {path:'',component:HomeComponent},
  {path:'login',component:LoginComponent},
  {path:'register',component:RegisterComponent}
]

and import them :

imports: [
    BrowserModule,
    RouterModule.forRoot(appRoutes)
  ],

I also used router-outlet in app component:

<router-outlet></router-outlet>>

I can navigate by URL or href, everything works fine, but routerLink is unclickable. When I hold the cursor over it, the cursor icon changes as if writing text.

My second problem is routerLink Property binding. It gives me an error. Code :

<li class="nav-item">
    <a class="nav-link" [routerLink]="['/register']">Register</a>
</li>

Error:

 Can't bind to 'routerLink' since it isn't a known property of 'a'.

31               <a class="nav-link" [routerLink]="['/register']">Register</a>

Any ideas ?


Solution

  • Check all the declarations into the app.module.ts file. Here you can find a working example of routerLink directive usage for your problem:

    https://stackblitz.com/edit/angular-ivy-tb2ssl?file=src/app/app.component.html