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?
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>