簡體   English   中英

如何使用角度6中的自定義指令渲染動態生成的內聯SVG

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM