2

I have the following code in my Angular app template, which does not work as expected:

<ng-container *ngFor="let item of items"">
   <a class="link"
      [attr.href]="item.url"
      [routerLink]="item.routerLink"
      rel="noopener noreferrer"
      tabindex="-1"
   >
     {{item.label}}
   </a>
<ng-container>
...

What I'm trying to do here is to iterate through an array of items and display list of links. The problem is that the item can either have url property, or routerLink. Depending on which property an item has, I need to either apply href attribute, or routerLink.

Is there a way to do that without using *ngIf which causes code duplication?

Nikita Marinosyan
  • 747
  • 2
  • 8
  • 26

2 Answers2

4

I suggest that you move the strategy to the component.ts

<a (click)="navigateToLink(item)">

and

navigateToLink( item ){
   if( item.routerLink ){
      this.router.navigate([item.routerLink]);
   }else if( item.url ){
      this.windows.open(item.url);
   }
}
Wandrille
  • 6,267
  • 3
  • 20
  • 43
  • 2
    I literally thought the same thing, (that's what I would have done or just using the *ngIf. I don't know if he just doesn't want to use `ifs` for a particular reason – Patricio Vargas Mar 15 '19 at 15:52
  • This is not recommended. href and click are different things, and click is likely to have poorer usability – cbp Mar 24 '21 at 14:43
1

Try the following

 <ng-container>
       <a class="link"
          [attr.href]="item.url ? item.url : ''"
          [routerLink]="item.routerLink ? item.routerLink: ''"
          rel="noopener noreferrer"
          tabindex="-1"
       >
         {{item.label}}
       </a>
    <ng-container>
Patricio Vargas
  • 5,236
  • 11
  • 49
  • 100