Search code examples
javascripttypescriptangularangular2-routing

Add element with RouterLink dynamically


When I put an anchor element in somewhere in an Angular component like this:

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

everything is working fine. When clicking the link, the Angular router navigates to the target component.

Now, I would like to add the same link dynamically. Somewhere in my app I have a "notification component", its single responsibility is to display notifications.

The notification component does something like this:

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

Where notification.content is a public string variable in the NotificationComponent class that contains the HTML to display.

The notification.content variable can contain something like:

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

Everything works fine and shows up on my screen, but nothing happens when I click the dynamic link.

Is there a way to let the Angular router work with this dynamically added link?

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


Solution

  • routerLink is a directive. Directives and Components are not created for HTML that is added using [innerHTML]. This HTML is not process by Angular in any way.

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

    For an example see Angular 2 dynamic tabs with user-click chosen components