[英]How to render dynamically generated inline SVG by using custom directive in angular 6
我在应用程序中渲染动态生成的内联SVG时遇到了困难。
我编写了一个自定义指令,它根据化学反应数据生成内联SVG。
RXN到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希望如此:
<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>
从模板调用指令,如下所示:
<div *appRxnToImage="reactionString"></div>
我想在div中渲染生成的内联SVG。
这样做来渲染SVG。
this.templateRef.elementRef.nativeElement.innerHTML = svg;
this.viewContainerRef.createEmbeddedView(this.templateRef);
有人可以帮我吗?
以下是修复程序的参考: https : //stackblitz.com/edit/g4j-structural-directive?file = src / main.ts
基本上在创建嵌入视图之后,您可以访问根节点(在您的示例中为div)并将innerHTML设置为它们( rxn-to-image.directive.ts的第37行)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.