这是我的场景。用户通过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>
发布于 2018-08-30 00:36:22
通过使用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
}
}
https://stackoverflow.com/questions/52068690
复制相似问题