FacundoGFlores FacundoGFlores - 2 months ago 6
TypeScript Question

Routerlink params with directives controlling it

I have the following code:

<a *ngIf="!menuItem.children" (mouseenter)="onHoverItem($event, item)" [routerLink]="[menuItem.url, menuItem.code]" [target]="menuItem.target" class="al-sidebar-list-link">
<i *ngIf="menuItem.icon" class="{{ menuItem.icon }}"></i><span>{{ menuItem.title }}</span>
</a>


But some links have the following
url
:

http://localhost:3000/URL/undefined


Because not all
menuItems
have the
code
set.

So I want to do the following in angular:

If the
menuItem.code
is set:

<a *ngIf="!menuItem.children" (mouseenter)="onHoverItem($event, item)" [routerLink]="[menuItem.url, menuItem.code]" [target]="menuItem.target" class="al-sidebar-list-link">
<i *ngIf="menuItem.icon" class="{{ menuItem.icon }}"></i><span>{{ menuItem.title }}</span>
</a>


Else:

<a *ngIf="!menuItem.children" (mouseenter)="onHoverItem($event, item)" [routerLink]="[menuItem.url]" [target]="menuItem.target" class="al-sidebar-list-link">
<i *ngIf="menuItem.icon" class="{{ menuItem.icon }}"></i><span>{{ menuItem.title }}</span>
</a>

Answer
<a *ngIf="!menuItem.children" 
   (mouseenter)="onHoverItem($event, item)" 

   [routerLink]="[menuItem.url, menuItem.code!=undefined?menuItem.code:'']" //<<<<<<<<<<<<  here

   [target]="menuItem.target" class="al-sidebar-list-link">
   <i *ngIf="menuItem.icon" class="{{ menuItem.icon }}"></i><span>{{ menuItem.title }}</span>
</a>