0

I have an array of items, which looks like this:

nav: any = [
  {
    name: 'Homepage',
    url: 'homepage'
    internal: false
  },
  {
    name: 'Section 1',
    hash: 'section-1'
    internal: true
  },
];

Now I need to ouput a list of a-elements. These should either contain a routerLink if internal is false – or they should become an internal anchor. I've tried:

<a class="link"
   *ngFor="for item of nav"
   [href]="item.internal ? '#' + item.hash : null"
   [routerLink]="item.internal ? null : item.url">
  {{ item.title }}
</a>

This renders homepage correctly, but Section 1 comes out wrongly:

<a class="link" href="/homepage">Homepage</a>
<a class="link" href="/">Section 1</a>

This is what I actually want:

<a class="link" href="/homepage">Homepage</a>
<a class="link" href="#section-1">Section 1</a>

How to achieve this correctly?

lampshade
  • 2,470
  • 3
  • 36
  • 74

2 Answers2

1

Try this...

<a class="link" *ngFor="for item of nav" [routerLink]="item.internal ? '#' + item.hash : item.url">
 {{ item.title }}
</a>

The routerLink replaces by href after render.

Alok Mali
  • 2,821
  • 2
  • 16
  • 32
  • Thanks for your answer. Tried that already. It results in `/%23section-1`, which doesn't seem valid. It also throws "*Cannot match any routes*". – lampshade Jul 08 '19 at 13:35
0

why not conditionally, use one or the other?

 <ng-container *ngIf="internal">
     show appropriate link
 </ng-container>

 <ng-container *ngIf="!internal">
     show appropriate link
 </ng-container>
John Kane
  • 4,383
  • 1
  • 24
  • 42
  • Thanks. And yeah, I could probably solve it like this. I was hoping for a more elegant and simpler solution. :) – lampshade Jul 08 '19 at 13:45