1

I tried to pass an click event to a button that is rendered using DomSanitizer. But the bounded method is not getting called when the button is clicked.

component.ts

    export class MyComponent {
       htmlElement = '<button class="btn btn-primary" (click)="onClick()">Add</button>';
    
    onClick() {
        console.log('submitted');
      }
    }

component.html

    <div [innerHtml]="htmlElement | sanitizer"></div>

pipe.ts

    import { Pipe, PipeTransform } from '@angular/core';
    import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
    
    @Pipe({
      name: 'sanitizer'
    })
    export class SanitizerPipe implements PipeTransform {
      constructor(private _sanitizer: DomSanitizer) {}
        transform(v: string): SafeHtml {
          return this._sanitizer.bypassSecurityTrustHtml(v);
        }
    }

button is displayed properly with style. But click event is not getting triggered.

Is there any fix or alternative solution for this?

JsNgian
  • 795
  • 5
  • 19

1 Answers1

2

This is because (click)="onClick() is angular and not 'normal' HTML. When you use it with innerhtml binding the angular is not translated to normal HTML but is left like it is, and the dom doesn't understand it.

In our project we tried to do a similar thing, but haven't found a solution for this to work with angular html. Eventually we decide for a completely different approach so we wouldn't have to use the innerhtml binding. If you have an option to solve this problem without injecting html like this that would be safer and easier.

See also this issue: ngModel, click not working in angular 4 in dynamically added html

Emmy
  • 3,493
  • 2
  • 16
  • 25