简体   繁体   English

innerHTML未设置SVG元素的值

[英]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. 我有一个正在运行的Angular 7应用程序,我想根据下拉选择来更新text元素的值。

eg: If the id of text element is 10, then update the value of text from 'hi' to 'hello'. 例如:如果text元素的id为10,则将text的值从“ hi”更新为“ 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. 我正在使用setProperty innerHTML更新文本的值,并且在Chrome中可以正常工作,但是如果我尝试在IE中更改文本值,则不会更新相同的行为。

<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 使用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. 实际上,不需要使用renderer,setProperty,innerHTML来设置SVG元素的值。 We can simply use textContent to set the value. 我们可以简单地使用textContent来设置值。 It works for all browsers. 它适用于所有浏览器。

pathElement: SVGTextElement;

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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