0

I'm developing Angular 8 app and I want to insert HTML with angular bindings into my page.

So, my html code is:

<button (click)="insertHtml()">Insert</button>
<div id="text"></div>

My angular code is:

insertHtml() {
    document.getElementById("text").innerHTML = '<span (click)="handleClick(' + this.item.id + ')" [hidden]="' + this.item.hidden + '">'
}

Html looks fine, but it doesn't show right css class and click handler.

Can I insert html with angular bindings dynamically? And if yes, what am I doing wrong?

A. Gladkiy
  • 3,134
  • 5
  • 38
  • 82
  • You can check https://stackoverflow.com/questions/43682801/angular2-add-html-to-dynamic-elements or https://stackoverflow.com/questions/48913344/angular-5-adding-html-content-dynamically – Caro Nov 19 '19 at 15:41
  • [Here](https://dzone.com/articles/how-to-dynamically-create-a-component-in-angular) they show how to create components dynamically – dcg Nov 19 '19 at 15:41
  • @A. Gladkiy my answer is it work? – Doflamingo19 Nov 20 '19 at 13:41
  • @Doflamingo19 yes, it works, but unfortunately I need to insert my html into table row and here it didn't help me. – A. Gladkiy Nov 20 '19 at 13:58

1 Answers1

1

you can use another approch (something like this):

<button (click)="showHtml()">Insert</button>
<ng-container *ngIf="clicked">
 <div id="text"><span (click)="......" [hidden]="' + ...... + '">'</div>
</ng-container>

and in you .ts you do:

 @Input()
clicked:boolean =false;

showHtml(){
 this.clicked=true;
}

it must work.

Doflamingo19
  • 1,591
  • 4
  • 12
  • 32