Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
956 views
in Technique[技术] by (71.8m points)

templates - Insert XML into DOM in Angular 2

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.

UPDATE:

I've got some XML as a string that would I like to display in a template.

Pseudo-code:

const xml = 'valid xml string';

in component:

@Component({
  selector: "toolbox",
  template: `{{xml}}` <-- gives me xml as a string into DOM
});

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?

UPDATE SOLVED

Using DomSanitizationService, and [outerHTML], I was able to correctly output my XML string into the DOM.

Pseudo-code:

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');
  }

...

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
@Component({
  selector: "toolbox",
  template: `<div [innerHTML]="xml"></div>`
})
class MyComponent {
  xml = 'someXmlString';
}

See also In RC.1 some styles can't be added using binding syntax about how to fix sanitization issues.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...