Reputation: 660
I'm having difficulty in rendering dynamically generated inline SVG in my application.
I have written a custom directive which generates inline SVG from a chemical reaction data.
rxn-to-image.directive.ts
@Directive({
selector: '[appRxnToImage]'
})
export class RxnToImageDirective implements OnInit {
@Input()
set appRxnToImage(rxnString: any) {
this.generateImageFromRxn(rxnString);
}
constructor(
private templateRef: TemplateRef<any>,
private viewContainerRef: ViewContainerRef,
private renderer: Renderer2,
private el: ElementRef
) {}
ngOnInit() {
}
private generateImageFromRxn(rxn) {
// custom method that generated inline svg dynamicaaly
MarvinJSUtil.getPackage('#marvinjs-iframe').then(marvinNameSpace => {
marvin = marvinNameSpace;
const exporter = customMethodThatCreatesExporter;
exporter.render(rxn).then(
svg => {
// once svg generated i will call applySvg method to render svg
this.applySvg(svg);
},
error => {
alert(error);
}
);
});
}
private applySvg(svg) {
this.templateRef.elementRef.nativeElement.innerHTML = svg;
this.viewContainerRef.createEmbeddedView(this.templateRef);
}
}
SVG would like this:
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100%" height="225" xmlns:ev="http://www.w3.org/2001/xml-events" style="overflow: hidden; "><</svg>
calling directive from the template like this:
<div *appRxnToImage="reactionString"></div>
I want to render generated inline SVG inside the div.
doing like this to render SVG.
this.templateRef.elementRef.nativeElement.innerHTML = svg;
this.viewContainerRef.createEmbeddedView(this.templateRef);
Anyone can please help me?
Upvotes: 3
Views: 1739
Reputation: 51
Here is a reference to the fix: https://stackblitz.com/edit/g4j-structural-directive?file=src/main.ts
Basically after you create the embedded view, you can access the root nodes (in your example the div) and set the innerHTML their (line 37 of rxn-to-image.directive.ts)
Upvotes: 1