简体   繁体   中英

innerHTML doesn't set the value of SVG element

I have a running Angular 7 application and I want to update the value of text element based on dropdown selection.

eg: If the id of text element is 10, then update the value of text from 'hi' to 'hello'.

I am using setProperty innerHTML to update the value of text and it works fine in Chrome, but If I am trying the same behavior in IE text value is not getting updated.

<text id='10'>hi</text>


svgElement: SVGElement;
pathElement: HTMLElement;

constructor(private renderer: Renderer2) { }

this.pathElement = svgElement.querySelector(`[id='10']`);
this.renderer.setProperty(this.pathElement, 'innerHTML', 'hello');

Use DomSanitizer

Try like this:

import { DomSanitizer } from '@angular/platform-browser'

constructor(private renderer: Renderer2, private domSanitizer: DomSanitizer){}

this.pathElement = svgElement.querySelector(`[id='10']`);
this.renderer.setProperty(this.domSanitizer.bypassSecurityTrustHtml(this.pathElement), 'innerHTML', 'hello');

I didn't realize the answer will be pretty simple. Actually, there is no need to use renderer, setProperty, innerHTML to set the value of SVG element. We can simply use textContent to set the value. It works for all browsers.

pathElement: SVGTextElement;

this.pathElement = svgElement.querySelector(`[id='10']`);
this.pathElement.textContent = 'hello'

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