htmlangularrouterlink

Angular 8 routerLinks create decoded href with # to %23


I have one problem with generating routerLinks in my application. I retrieve the menu structure from API. Fetch it when app initializes, store it in the Observable and then simply show it.

The part of the structure im showing is pretty straightforward.

<ng-container *ngFor="let item of menuItems">
  <h5 class="dekstop-submenu-heading">{{ item.name }}</h5>
    <ul class="desktop-submenu-list" [ngClass]="{'desktop-submenu-list-wrap': item.subItems.length > 5}">
      <li *ngFor="let subItem of item.subItems" class="desktop-submenu-item">
        <a [attr.aria-label]="subItem.name" [routerLink]="subItem.url">{{ subItem.name }}</a>
      </li>
    </ul>
</ng-container>

The problem comes when there is an url with an anchor to specific page part, i.e. /some-component/description#specific. Angular routerLink is generated properly but the href isn't, it is decoded to /some-component/description%23specific. I can't get rid of this behaviour, I've tried decoding it with decodeURIComponent but with no effects..

Do you have any idea what causes such behaviour? Such a simply thing makes a lot of troubles..


Solution

  • You just need to send the url and the element id in a separate directive.

    If you have control over the subItem.url then just rename it to /description and subItem.fragment to specific and then change the template like this:

    [routerLink]="subItem.url" [fragment]="subItem.fragment"
    

    If you don't have control over subItem.url, then just perform a split on %23:

    const [url, ...fragment] = subItem.url.split('%23');
    
    [routerLink]="url" [fragment]="fragent.join('%23')"