1

Yo, I've got following situation: I have an angular service, which makes a HTTP request for some HTML code to backend. I am inserting HTML coming from backend into component's html with <div [innerHTML]="..."/>, right after it is received. The problem is that inside loaded HTML there is a button which have to trigger some action. I would like to use standard (click)="function()" binding, but Angular is not resolving it after 'injecting' the HTML from backend into innerHTML. Is there any way to do it?

admly
  • 319
  • 2
  • 10

1 Answers1

1

That's by design. Angular doesn't process HTML added by [innerHTML]="..." (except sanitization) in any way. It just passes it to the browser and that's it.

If you want to add HTML dynamically that contains bindings you need to wrap it in a Angular component, then you can add it using for example ViewContainerRef.createComponent()

For a full example see Angular 2 dynamic tabs with user-click chosen components

A less Angulary way would be to inject ElementRef, accessing the added HTML using

elementRef.nativeElement.querySelector('a').addEventListener(...)
Atul Stha
  • 1,404
  • 8
  • 23
  • 46
  • Thanks, I'll check the example you provided. I think I can't use ElementRef, because HTML is actually an list with multiple items - and each item has it's button to fire an action. – admly Jul 23 '19 at 06:30
  • You can break it down before hand and provide the transformed data. – Atul Stha Jul 23 '19 at 06:33
  • I did it like in this https://netbasal.com/dynamically-creating-components-with-angular-a7346f4a982d and this https://jaxenter.com/dynamically-create-component-angular-142720.html and nothing has changed, bindings are not resovled. I am loading component via COmponentFactoryResolver. – admly Jul 23 '19 at 07:24
  • i would suggest you replicate the issue in stackblitz. – Atul Stha Jul 23 '19 at 08:44