将指令附加到动态添加的元素 [英] Attaching directives to dynamically added elements

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

问题描述

当您使用另一个元素的ElementRef.nativeElement.innerHTML属性将带有指令的元素添加到DOM时,该指令不会触发.如何以一种导致指令触发的方式向DOM中添加元素?

When you add an element with a directive to the DOM using another element's ElementRef.nativeElement.innerHTML property, the directive does not fire. How do I add an element to the DOM in a way that causes the directive to fire?

示例
如果在我的组件中执行以下操作:

Example
If in my component I do something like the following:

export class AppComponent implements OnInit {

    constructor(private _elem: ElementRef) { }    

    ngOnInit() {
        this._elem.nativeElement.innerHTML = '<span myDirective>Foo</span>';
    }

}

(这是对我实际实现的主要简化,因此我们暂时忽略这是一种不好的做法)

(This is a major simplification over my actual implementation, so let's ignore that this is bad practice for a second)

然后,似乎已附加到<span>myDirective永远不会真正运行.

Then the myDirective that appears to be attached to the <span> will never actually run.

问题是:我如何利用指令识别新元素以便其运行?

The question is: how do I get angular to recognize the new element with the directive so that it runs?

推荐答案

即时编译已从Angular 2+中删除.另一种使用动态组件加载器动态加载组件的方法.为此,您必须更改现有的实施方式

On the fly compilation is removed from Angular 2+. Another Alternative loading components dynamically using Dynamic Component Loader. For this you have to change your existing implementation

https://angular.io/guide/dynamic-component-loader

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

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