Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RouterLink inside a repeater angular 2

There is a routerLink that enables the necessary routes for navigation provided with the config.

It works fine, if it is done something like below:

<ul class="nav">
    <li class="nav-item">
        <a class="nav-link" href="#" [routerLink]="['/home']">Home</a>
    </li>
    <li class="nav-item">
        <a class="nav-link" href="#" [routerLink]="['/about']">About</a>
    </li>
</ul>

But it fails when used inside a *ngFor repeater, like this

<ul class="nav">
    <li class="nav-item" *ngFor="let item of menu">
        <a class="nav-link" href="#" [routerLink]="['{{item.link}}']">{{item.name}}</a>
    </li>
</ul>

I have searched enough on Google but I wasn't able to find a satisfying answer.

Any help is appreciated

like image 610
Arunkumar Srisailapathi Avatar asked Aug 10 '16 06:08

Arunkumar Srisailapathi


People also ask

What does routerLink do in Angular?

In Angular, RouterLink is a directive for navigating to a different route declaratively. Router. navigate and Router. navigateByURL are two methods available to the Router class to navigate imperatively in your component classes.

Can I use routerLink on button?

Using Router linksAfter Angular v4 we can directly add a routerLink attribute on the anchor tag or button. Consider the following template, where routerLink attribute added to the anchor tag. The routerLink directive on the anchor tags give the router control over those elements.

Does routerLink work on Div?

Yes it can be attached to div tag, your route is probably wrong try add / in front of route.

What is the main difference between HREF and routerLink in an Angular application?

Href is the basic attribute provided by Html to navigate through pages which reloads the page on click. routerLink is the attribute provided by angular to navigate to different components without reloading the page.


1 Answers

You don't need '{{item.link}}'

Use only item.link without '' and {{}}

<ul class="nav">
     <li class="nav-item" *ngFor="let item of menu">
         <a class="nav-link" href="#" [routerLink]="[item.link]">{{item.name}}</a>
     </li>
</ul>

If you want to concatenate the routerLink

you can do

[routerLink]="['./page/' + item.id]"
like image 113
Suren Srapyan Avatar answered Sep 30 '22 18:09

Suren Srapyan