如何让 Angular 2 选择动态添加的 routerLink 指令 [英] How to make Angular 2 pick up dynamically added routerLink directive

查看:27
本文介绍了如何让 Angular 2 选择动态添加的 routerLink 指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如在 this plunker 中所见,我正在向其中一个动态添加 HTML我的元素,归结为:

As seen in this plunker, I'm dynamically adding an HTML to one of my elements, which boils down to this:

@Component({
    selector: 'my-comp',
    template: `<span [innerHTML]="link"></span>`,
}) export class MyComponent {
    private linkContent = '<a routerLink="/my-route">GoTo Route</a>';
    private link;

    constructor(sanitizer: DomSanitizer) {
        this.link = sanitizer.bypassSecurityTrustHtml(linkContent);
    }
}

这导致 <a routerLink="/my-route">GoTo Route</a> 被添加到 DOM,但 Angular 对 routerLink 指令在这个元素上,并且不绑定"到它.因此,当您单击该链接时,它会通过重新引导程序完全重新加载(这在 plunk 中不起作用,它只会给出 404).

This results in <a routerLink="/my-route">GoTo Route</a> being added to the DOM, but Angular knows nothing about the routerLink directive on this element, and does not "bind" to it. So, when you click the link, it results in complete reload with re-bootstrap (which doesn't work in plunk, it just gives a 404).

问题:如何告诉 angular 遍历 DOM(或其部分,甚至单个元素)并在需要时执行组件初始化?

Question: how to tell angular to go through the DOM (or its part, or even a single element) and perform component initialization if needed?

推荐答案

Angular2 不处理以任何方式动态添加的 HTML,除了清理.

Angular2 doesn't process HTML added dynamically in any way except sanitization.

'<a routerLink="/my-route">GoTo Route</a>' 传递给 innerHTML 就是这样做的,将此字符串传递给DOM,但没有别的.没有实例化或应用 routerLink 指令.

Passing '<a routerLink="/my-route">GoTo Route</a>' to innerHTML is doing exactly this, passing this string to the DOM, but nothing else. There is no routerLink directive being instantiated or applied.

如果您需要动态添加使用 Angular2 绑定、指令或组件的 HTML,您可以将 HTML 添加到组件模板,并使用 ViewContainerRef.createComponent() 动态添加此组件,如演示例如在 Angular 2 动态标签与用户-单击所选组件

If you need to add HTML dynamically that uses Angular2 bindings, directives, or components, you can add the HTML to a components template, and add this component dynamically using ViewContainerRef.createComponent() like demonstrated for example in Angular 2 dynamic tabs with user-click chosen components

这篇关于如何让 Angular 2 选择动态添加的 routerLink 指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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