Blake Rivell Blake Rivell - 6 months ago 24
Javascript Question

Creating a 'view' link in a grid listing that navigates to a detail route such as hero/:id in Angular

In my template I am doing the following:

<tbody>
<tr *ngFor="let h of heroes">
<td>{{ h.id}}</td>
<td>{{ h.name}}</td>
<td>{{ h.description}}</td>
<td><a href="">View</a></td>
</tr>
</tbody>


How can I make it so View is a link that navigates to /heroes/:id? I have this setup in my route config. I verified that it works by going to http://localhost:4200/heroes/1

Am I better off using the (click) event and calling a function such as viewHero(id). If I did this I wouldn't be sure how to pass the id. Also, if it can be done directly inside of the html template within the href tag or routerLink I would like to know how to do that too. My main problem seems to be accessing h.id inside of a string such as href="".

Update: I got the following to work, but still not happy with it:

<td><a (click)="viewHero(h)">View</a></td>

viewHero(hero) {
this.router.navigate(['/heroes', hero.id]);
}


There has to be a way to simply do this inside of the anchor tag directly. I am not getting a pointer finger when hovering the link.

Answer Source

Try this:

<tbody>
  <tr *ngFor="let h of heroes">
    <td>{{ h.id}}</td>
    <td>{{ h.name}}</td>
    <td>{{ h.description}}</td>
    <td><a routerLink="/heroes/{{h.id}}">View</a></td>
  </tr>
</tbody>