Adding an item with RouterLink dynamically

When I put an anchor element in some component of angular 2, for example,

<a [routerLink]="['/LoggedIn/Profile']">Static Link</a> 

everything is working fine. When clicking the link, the angular router directs me to the target component.

Now I would like to add the same link dynamically. Somewhere in my application, I have a “notification component” in which one responsibility is to display notifications.

The notification component does something like this:

  <div [innerHTML]="notification.content"></div> 

where notification.content is a string variable in the NotificationComponent class and contains the displayed HTML.

The notification.content variable may contain something like

  <div>Click on this <a [routerLink]="['/LoggedIn/Profile']">Dynamic Link</a> please</div> 

Everything works fine and appears on my screen, but nothing happens when I click on a dynamic link?

Is there any way to allow the angular router to work with this dynamically added link ???

ps. I know about DynamicComponentLoader, but I really need a more unlimited solution where I can send all kinds of HTML to my notification component with all kinds of different links ....

+7
javascript angular typescript angular2-routing
source share
1 answer

routerLink is a directive. Directives and components are not created for HTML, which is added using [innerHTML] . This HTML is not an Angular process.

The recommended way is not to use [innerHTML] , but DynamicComponentLoader ViewContainerRef.createComponent , where you wrap HTML in the component and dynamically add it.

For an example, see Angular 2 dynamic tabs with user-selected components of your choice

+1
source share

All Articles