RouterLink does not work properly

I have an app that works with RouterLink.

Here is the imports array in the App Module:

imports: [
    BrowserModule,
    RouterModule.forRoot([
      {path: '', component: HomeComponent},
      {path:'contact', component: ContactComponent},
      {path: 'about/:id/:name', component: AboutComponent}
    ])

And this is the app.component.html:

<div>
  <a routerLink="" routerLinkActive="active">Home</a>
  <a routerLink="/contact" routerLinkActive="active"> Contact</a>
</div>
<router-outlet></router-outlet>

On the Home if the user clicks on About this user, it should be redirected to a an About page for a specific user:

<div>
  <a [routerLink]="['/about', follower.id, follower.name]">About this user { ... </a>
</div>

However, when the app loads, I get this error on console: Cannot read property 'id' of undefined

Could you please help me find out what is wrong?

Upvotes: 0

Views: 194

Answers (2)

Sanoj_V
Sanoj_V

Reputation: 2986

Check object key is present or not by using ? operator like this:

<div>
   <a [routerLink]="['/about', follower?.id, follower?.name]">About this user { ... </a>
</div>

Upvotes: 1

Sajeetharan
Sajeetharan

Reputation: 222522

use safe navigation operator as follows,

 <a [routerLink]="['/about', follower?.id, follower?.name]">About this user { ... </a>

Upvotes: 1

Related Questions