Search code examples
angularangular-directive

How to add conditional fragment with it's value to the anchor html tag in Angular 5


I'm loading menus from service and need to conditionally add the fragment to anchor. here the problem is fragment add # for the empty value and don't want to add # in URL for an empty fragment.

see the following HTML code of navbar component.

<ul class="nav navbar-nav">
    <li *ngFor="let menu of menus">
       <a [routerLink]="menu.menuUrl" [title]="menu.name" here need to add fragment with it's value if menu.fragment present>
          <span>{{menu.name}}</span>
       </a>
    </li>
</ul>

Solution

  • What you could do is use ngSwitch to display the menu according to the value of menu.fragment

    <ul class="nav navbar-nav">
      <li *ngFor="let menu of menus" [ngSwitch]="menu.fragment !== undefined">
        <a *ngSwitchCase="true" [fragment]="menu.fragment" [routerLink]="menu.menuUrl" [title]="menu.name">
          <span>{{menu.name}}</span>
        </a>
        <a *ngSwitchDefault [routerLink]="menu.menuUrl" [title]="menu.name" >
          <span>{{menu.name}} no frag</span>
        </a>
      </li>
    </ul>
    

    You can find a running example https://stackblitz.com/edit/angular-fxp2dx