这是我的场景。用户通过 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/