Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...