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.

1

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

The whole button tag is coming as an string from a service. So nothing at design time.
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 ?
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.

1 Comment

The whole button tag is coming as an string from a service. So nothing at design time.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.