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

...

}
wincelet
  • 63
  • 1
  • 5

1 Answers1

2
@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.

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • I tried by this and was very confused by the output. With the added DomSanitizerService added in I'm still seeing the output with the xml as a string. In addition the added
    is an issue as well. I need someway to output just the xml. Here's what I see with this suggested change:
    ...
    – wincelet Aug 31 '16 at 15:14
  • You can use `[outerHTML]` instead of `[innerHTML]` then the `div` should be replaced by the content. – Günter Zöchbauer Aug 31 '16 at 15:27
  • Thanks! this appears to have worked, though now I may have a load timing issue. I really appreciate your fast response! – wincelet Aug 31 '16 at 17:32
  • What you mean with "load timing issues"? – Günter Zöchbauer Aug 31 '16 at 17:34
  • My external library isn't seeing the xml at the time it's trying to generate the SVG, I'll play around with it a bit though. Thanks again. – wincelet Aug 31 '16 at 17:42
  • Where do you initialize the external library? You need to wait for `ngAfterViewInit()` to be called. – Günter Zöchbauer Aug 31 '16 at 17:43