【问题标题】:Angular 5 dynamically insert a component into existing markup?Angular 5 将组件动态插入到现有标记中?
【发布时间】:2019-02-03 17:25:27
【问题描述】:

这是我的场景。用户通过 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();
    }
}

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

&lt;p&gt;This is my content from the server. &lt;img src="..." /&gt;&lt;/p&gt;

那么我的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>

【问题讨论】:

  • 所以基本上您需要做的是使用您从服务器获取的模板创建一个动态组件。对吗?
  • @AnuradhaGunasekara 是的,这就是我需要的

标签: angular dynamic


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-06
    • 2019-12-08
    • 2011-02-14
    • 2018-07-02
    • 1970-01-01
    • 2019-01-07
    相关资源
    最近更新 更多