Reputation: 6936
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.
Upvotes: 0
Views: 65
Reputation: 183
Angular 2/4/5 doesn't process HTML added dynamically.Click event will not work.
Upvotes: 0
Reputation: 4156
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.
Upvotes: 0
Reputation: 725
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.
Upvotes: 1