简体   繁体   中英

How to render dynamically generated inline SVG by using custom directive in angular 6

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?

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM