12

I have a simple angular 2 component:

@Component({
  selector: 'test-text',
  template: `<p> Text </p>`
})
export class TestComponent {
  constructor() {}      
  getHtmlContent() {return;} //This should return '<p> Text </p>' as a string
}

What is the simplest way I can the html content for my Component back?

Kim Kern
  • 54,283
  • 17
  • 197
  • 195
swapp1990
  • 454
  • 1
  • 5
  • 16

1 Answers1

17

You can use ElementRef. E.g.

import { Component, ElementRef } from '@angular/core';

@Component({
  selector: 'test-text',
  template: `<p> Text </p>`
})
export class TestComponent {
  elRef: ElementRef

  constructor(elRef: ElementRef) {
    this.elRef = elRef;
  }      

  getHtmlContent() {
    //This will return '<p> Text </p>' as a string
    return this.elRef.nativeElement.innerHTML;
  }
}
tjoskar
  • 443
  • 3
  • 13
  • 7
    This gives you DOM-translated html, which excludes all bindings. It does not give you the actual `component.template` – allenhwkim Dec 15 '16 at 15:19
  • 1
    @allenhwkim This answer shows how you can get the component.template: https://stackoverflow.com/questions/45497561/is-there-a-way-to-get-the-html-template-for-an-angular-component#answer-45499616 – peinearydevelopment Aug 11 '17 at 17:46