使用 RouterLink 动态添加元素 [英] Add element with RouterLink dynamically

查看:34
本文介绍了使用 RouterLink 动态添加元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我像这样在 Angular 组件的某处放置一个锚元素时:

静态链接

一切正常.单击链接时,Angular 路由器会导航到目标组件.

现在,我想动态添加相同的链接.在我的应用程序的某个地方,我有一个通知组件",它的唯一职责是显示通知.

通知组件做这样的事情:

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

其中 notification.contentNotificationComponent 类中包含要显示的 HTML 的公共字符串变量.

notification.content 变量可以包含如下内容:

点击这个动态链接

一切正常并显示在我的屏幕上,但当我点击动态链接时没有任何反应.

有没有办法让 Angular 路由器使用这个动态添加的链接?

PS:我知道 DynamicComponentLoader,但我真的需要一个更不受限制的解决方案,我可以将各种 HTML 发送到我的通知组件,以及各种不同的链接.

解决方案

routerLink 是一个指令.指令和组件不是为使用 [innerHTML] 添加的 HTML 创建的.Angular 不会以任何方式处理此 HTML.

推荐的方式是不使用 [innerHTML] 而是 DynamicComponentLoaderViewContainerRef.createComponent 将 HTML 包装在组件中并动态添加.

有关示例,请参阅 Angular 2 动态选项卡与用户-单击所选组件

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.

解决方案

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

这篇关于使用 RouterLink 动态添加元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆