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

时间:2018-08-29 02:33:42

标签: 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>

1 个答案:

答案 0 :(得分:0)

通过解决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
    }
}