在Angular 2中将XML插入DOM [英] Insert XML into DOM in Angular 2
问题描述
我对Angular 2还是很陌生,确实很难解决如何将XML添加到我的html模板中.我想有条件地将特定的XML集插入到我的模板中,外部库从该模板中渲染一些SVG.我将XML集作为js字符串,试图在模板中进行插值.
I'm fairly new to Angular 2 and am really having a hard time trying to figure out how to add XML to my html template. I would like to conditionally insert specific sets of XML into my template from which an external library renders some SVG. I have my XML sets as js strings which I'm trying to interpolate in my template.
更新:
我有一些XML,希望将其显示在模板中.
I've got some XML as a string that would I like to display in a template.
伪代码:
const xml = 'valid xml string';
在组件中:
@Component({
selector: "toolbox",
template: `{{xml}}` <-- gives me xml as a string into DOM
});
我已经尝试过首先在xml上使用DOMParser,但随后我只得到一个表示[object XMLDocument]的字符串.我试图以此方式进行操作,以便可以根据用户输入更改xml,而以前的工作只是将XML放入模板中.也许有一种方法可以动态交换组件模板?
I've tried using DOMParser on the xml first, but then I just get a string that says [object XMLDocument]. I was trying to do it this way so that I could change the xml based on user input, what worked before was simply putting the XML into the template. Perhaps there is a way to swap component templates dynamically?
已解决
使用 DomSanitizationService 和 [outerHTML] ,我能够将XML字符串正确输出到DOM中.
Using DomSanitizationService, and [outerHTML], I was able to correctly output my XML string into the DOM.
伪代码:
import { DomSanitizationService, SafeHtml } from '@angular/platform-browser';
@Component({
...
template: `<div [outerHTML]="xml"></div>`
...
})
export class MyClass {
xml: SafeHtml;
constructor(sanitizer: DomSanitizationService){
this.xml = sanitizer.bypassSecurityTrustHtml('my valid xml string');
}
...
}
推荐答案
@Component({
selector: "toolbox",
template: `<div [innerHTML]="xml"></div>`
})
class MyComponent {
xml = 'someXmlString';
}
另请参见在RC.1关于如何解决卫生问题的某些样式无法使用绑定语法添加.
这篇关于在Angular 2中将XML插入DOM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!