Angular 5 动态地将组件插入现有标记?

标签 angular dynamic

这是我的场景。用户通过 tinyMCE 编辑器输入内容,我在组件中将这些内容显示给用户,如下所示:

@Component({
    template: '
        <h3>Description</h3>
        <div [innerHTML]="content"></div>
    '
})
export class DetailsComponent implements OnInit {

    content: string = "";

    constructor(private service: any){}

    ngOnInit(){
        this.service.loadDetails().pipe(
            tap((result) => this.content = result)
        ).subscribe();
    }
}

现在来自服务器的内容可以是任何内容。所以如果服务器返回这个内容:

<p>This is my content from the server. <img src="..." /></p>

然后是我的DetailsComponent输出看起来像这样:

<h3>Description</h3>
<div>
    <p>This is my content from the server. <img src="..." /></p>
</div>

我想编写一个组件来用自定义组件替换任何图像。在不使用现有#template 引用的情况下如何做到这一点?

重要的是,我的自定义组件包装图像可能看起来像这样:

<h3>Description</h3>
<div>
    <p>This is my content from the server. <custom-component><img src="..." /></custom-component></p>
</div>

最佳答案

通过解决问题找到了解决方案 this SO example

这是我解决问题的方法。

update() {

    let images = this.el.nativeElement.querySelectorAll('img');

    for (let x = 0; x < images.length; x++) {
        const img = images[x];

        let clone = img.cloneNode(true);
        // Important because angular removes all children of a node. 
        // So wrap the image, and then use the wrapper as the root node for the component to attach to
        $(img).wrap("<span />");
        let factory = this.factoryResolver.resolveComponentFactory(CustomComponent);
        let ref = factory.create(this.injector, [[clone]], img.parentNode); //use a clone as the projectable node, and use its parent (the wrapper span) as the rootNode

        this.applicationRef.attachView(ref.hostView);
        ref.changeDetectorRef.detectChanges();
        this.components.push(ref); //save the references later so that I can destroy them
    }
}

关于Angular 5 动态地将组件插入现有标记?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52068690/

相关文章:

python - 动态变量创建

c# - 如何在 C# 中开发基于动态插件的功能

c# - 带有数字键的动态 json 对象

javascript - 用于将数据传递到组件到组件的 Angular 2 共享服务

javascript - 如何以 Angular 将 JSON 传递给@Input?

javascript - Angular2 CanActivate 守卫除一条路线外的所有路线

angular - 将 Angular 7 更新为 Angular 9 后,无法读取 null 的属性 'fileName' 中的错误

java - 在运行时向 Hibernate 实体动态添加字段

c# - 从 xml 和 c# 创建具有层次结构的动态对象

angular - 路由中可变数量的参数