Add element with RouterLink dynamically

孤街浪徒 提交于 2019-12-04 01:26:46

问题


When i put an anchor element in someweher in a angular 2 Component like this,

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

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

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

The notifications component does something like this:

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

where notification.content is the string variable in the NotificationComponent class, and 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....


回答1:


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



来源:https://stackoverflow.com/questions/36310288/add-element-with-routerlink-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!