RouterLink inside a repeater angular 2

12,510

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]"
Share:
12,510
Arunkumar Srisailapathi
Author by

Arunkumar Srisailapathi

Inclined to technologies

Updated on July 10, 2022

Comments

  • Arunkumar Srisailapathi
    Arunkumar Srisailapathi almost 2 years

    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

  • Arunkumar Srisailapathi
    Arunkumar Srisailapathi over 7 years
    Thanks! Worked like a charm
  • valignatev
    valignatev over 7 years
    @Arun Kumar Don't forget to accept an answer if it works for you. So other folks could easily find it.
  • Matt Burland
    Matt Burland about 6 years
    Any chance you could add a why? You don't need ... because...?
  • Greg
    Greg almost 4 years
    @ShaneCourtrille Because Angular already evaluates the contents of angular tag properties. {{ }} is for use outside of angular properties, like between tags. If it's not a standard html element property, but instead one added as part of angular, then you're already golden.