0

I am trying to ad a Button and event to it at runtime. e.g.

  str1 = `
    <button type="button" (click)='alert1()'>Click Me!</button>
  `
  constructor(private sanitizer: DomSanitizer) { }

  safeStr() {
    return this.sanitizer.bypassSecurityTrustHtml(this.str1);
  }

  alert1() {
    alert('me')
  }

In template :: <span [innerHTML]="safeStr()"></span>

The button is rendering but click event not working. Can anyone help please.

raju
  • 6,448
  • 24
  • 80
  • 163

3 Answers3

1

The HTML is interpreted by the browser, that's why you see the button. The JS however is generated at compile time. You should do something much simpler : hide the button if not needed, with a code that looks like :

<button *ngIf="isButtonDisplayed" type="button" (click)="alert1()">Click Me !</button>

And in component, add a isButtonDisplayed boolean value that you switch from false to true at runtime.

Wis
  • 705
  • 1
  • 11
  • 34
  • The whole button tag is coming as an string from a service. So nothing at design time. – raju Apr 11 '18 at 08:45
  • Ho, that's a point you did not mention. When you say that the button is coming from service, what exactly you mean ? Does your service get this code from a backend ? Or does the service construct it based on some logic ? – Wis Apr 11 '18 at 08:53
0

Seems to me that what you are trying to achieve is to just show the button. In that case you should use *ngIf

Like this

template:

<button *ngIf="someBooleanCondition" type="button" (click)='alert1()'>Click Me!</button>

If you really need to inject template in runtime, it should be still possible, at least according to this article - https://blog.thecodecampus.de/angular-2-dynamically-render-components/

However it seems like a really weird and complicated scenario, to load buttons from external service. Using *ngIf together with some config object coming from that service would be imho much easier.

David Votrubec
  • 3,968
  • 3
  • 33
  • 44
  • The whole button tag is coming as an string from a service. So nothing at design time. – raju Apr 11 '18 at 08:45
0

Angular 2/4/5 doesn't process HTML added dynamically.Click event will not work.

Akshay Kapoor
  • 185
  • 1
  • 3