Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get html template of an Angular 2 Component?

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?

like image 658
swapp1990 Avatar asked Nov 22 '16 21:11

swapp1990


1 Answers

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;
  }
}
like image 128
tjoskar Avatar answered Sep 27 '22 22:09

tjoskar