m41n
m41n

Reputation: 453

html (template) generated out of vaiable data

I have a basic typescript file for an angular 2 (or 4 rather) application like this:

// imports

@Component({
  selector: 'app-component',
  template: `<div>HELLO</div>` // <- this template
})
export class Component implements OnInit {

  constructor() {}

  ngOnInit() {
  }

}

Now my question is: is it possible to have the template above, which holds the components html be generated out of a variable?

As for more detailed information: I am getting a json object from my backend that contains a property "html" which holds an entire html file which I want to display. I will probably load this in the ngOnInit, now I just don't know how I can tell angular to use it for the template.

Upvotes: 0

Views: 37

Answers (1)

Raed Khalaf
Raed Khalaf

Reputation: 2065

this is a simple component, that contains only div element.

you can simply bind the [innerHtml] property on the div element with the data returned from backed.
in the component class i use ngOnInit life-cycle hook in order to request the template from the backend.

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


@Component({
  selector: 'my-app',
  template: `
    <div [innerHtml]='myTemplate'>
    </div>
    `
})
export class AppComponent implements OnInit{
  myTemplate = '';

  ngOnInit() {
    setTimeout(() => { 
      this.myTemplate = '<h1> Raed Khalaf </h1>'
    }, 1000);
  }
}

Upvotes: 1

Related Questions