首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Angular 5在现有的标记中动态插入组件?

Angular 5在现有的标记中动态插入组件?
EN

Stack Overflow用户
提问于 2018-08-29 10:33:42
回答 1查看 89关注 0票数 3

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

代码语言:javascript
运行
复制
@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输出将如下所示:

代码语言:javascript
运行
复制
<h3>Description</h3>
<div>
    <p>This is my content from the server. <img src="..." /></p>
</div>

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

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

代码语言:javascript
运行
复制
<h3>Description</h3>
<div>
    <p>This is my content from the server. <custom-component><img src="..." /></custom-component></p>
</div>
EN

回答 1

Stack Overflow用户

发布于 2018-08-30 00:36:22

通过使用this SO example找到了解决方案

下面是我是如何解决这个问题的。

代码语言:javascript
运行
复制
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
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52068690

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档