The simplest way to add html to DOM using Angular


To add html to DOM using Angular may be tricky and there are many solutions on this problem but after a lot of searching and a lot of trial and error I 've found the simplest solution(what did you expect ? )

I wanted to implement a text editor when the input is a simple text that you can modify with many ways(list,numbered list, bold,italic font etc) and the output is html.

With the following code this html becomes a part of the DOM tree.

component.component.ts

export class .... implements OnInit{
....
//static content
htmlVariable: string;
//dynamic content
htmlValues: any[] =["test","test1"]
..

ngOnInit(){
this.htmlVariable = "Test"
  }
}

component.component.html

//static content

 <p [innerHtml]='htmlVariable'>

//dynamic content
<div class="container" *ngFor="let item of htmlValues; let i = index">
 <p [innerHtml]='htmlValues[i]'></p>
</div>

Σχόλια