0

If I build an HTML template using routing, like here

<ul class="sb-sub-menu">
    <li>
        <a [routerLink]="['clientadd']">Client Add</a>
    </li>
</ul>

This works as I would expect.

However, if I was building a dynamic UI from a HTML formatted string, the routing doesn't seem to apply.

<ul class="sb-sub-menu" [innerHTML]="links"></ul>

where

links: string = `
<li>
   <a [routerLink]="['clientadd']">Client Add</a>
</li>`

In my situation, the list of links is more complicated and I wanted to see if there was a way to load them as templated HTML, instead of needing to create a model.

Is there such a way to load a templated HTML string and have routing working?

Oblivion2000
  • 616
  • 4
  • 9

2 Answers2

1

Angular doesn't process dynamically added HTML in any way. No bindings, no directive or component instantiation, ... except sanitization for security purposes.

You can use ViewContainerRef.createComponent() to dynamically add components like explained in Angular 2 dynamic tabs with user-click chosen components

If you really need dynamic HTML (for example user-provided) you can use the approach explained in How to realize website with hundreds of pages in Angular2

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
1

You can try to create links dynamically using *ngFor instead of using innerHtml

For e.g.

<ul class="sb-sub-menu">
  <li *ngFor="let item of menuItems">
    <a [routerLink]="[item.url]">{{item.label}}</a>
  </li>
</ul>
Ajay Ambre
  • 89
  • 6