如何使Angular 2拾取动态添加的routerLink指令 [英] How to make Angular 2 pick up dynamically added routerLink directive

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

问题描述

此导航键中可以看到,我正在将HTML动态添加到其中之一我的元素,归结为:

@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指令一无所知,并且不对其进行绑定".因此,当您单击链接时,它会导致使用re-bootstrap进行完全重新加载(在plunk中不起作用,它只会显示404).

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

解决方案

Angular2不会处理除清理之外以任何方式动态添加的HTML.

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

如果需要动态添加使用Angular2绑定,指令或组件的HTML,则可以将HTML添加到组件模板,并使用ViewContainerRef.createComponent()动态添加此组件,如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);
    }
}

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).

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 doesn't process HTML added dynamically in any way except sanitization.

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.

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天全站免登陆