Reputation: 267
Currently I'm rendering the html string using innerHtml property after bypassing the angular sanitizing mechanism this is working for rendering the contents. But not able to map the event handlers to a function in angular component.
E.g.the html string will contain a button like below
<button (click)="callme()">Click</button>
the callme function will be part of angular component file. I want this click event to be handled in angular function.
Is it possible to parse this string to html dom and handle the events in angular components.
Sample code which describes this scenario and using angular cdk Portals. https://stackblitz.com/edit/angular-upaudh?file=src%2Fapp%2Fcdk-portal-overview-example.ts
Upvotes: 2
Views: 2865
Reputation: 2916
There are 2 ways that you can implement it, it depends from what you want.
HTML
<div [innerHTML]="htmlStr"></div>
TS
htmlStr: 'Hello';
PS: In your example (in the comments) you use [innerHtml]
and try to bind it in a Portal. Again [innerHtml]
will not be translated before runtime so your click event will not be in the same scope as your component. The thing that you ask is an open conversation in github: Issue. For now you can use the alternatives above to solve your case. You can use innerHtml
, and then use renderer2 or native element reference to bind click events to your functions, after they have rendered on the view.
Upvotes: 3