I want to create a button dynamically.I used innerHtml to do this. I can create button.But it's click event not working. Please tell me how to solve this?
Here is my html code
<div [innerHTML]="answerPanelContent"></div>
Here is my typescript code
answerPanelContent: any;
constructor(private sanitizer: DomSanitizer){
}
ngOnInit() {
this.answerPanelContent = this.sanitizer.bypassSecurityTrustHtml(`<button type="button" class="btn btn-primary float-left"
(click)="removeAnswer()" title="Remove Answer"
aria-label="Close">
Remove</button>`);
}
removeAnswer(){
alert('clicked');
}
Here is the stackblitz url: https://stackblitz.com/edit/angular-nka4w9
I strongly recommend not using [innerHTML] for this. It is not meant for this purpose and not the "angular way" at all.
This is the most preferable way to solve your issue and "the angular way".
component.ts
export class AppComponent {
public buttonsTexts:Array<string> = ['First button'];
public addButton(index:number):void {
this.buttonsTexts = [...this.buttonsTexts, `button ${index}`];
}
}
template.html
<button
*ngFor="let buttonText of buttonsTexts; let i = index;"
(click)="addButton(i)">{{buttonText}}</button>
StackBlitz
Use this only if *ngFor is not able to solve your issue because of some requirements that we don't know.
component.ts:
export class AppComponent implements AfterViewInit {
@ViewChild('inserttarget', {static: false})
public insertTarget:ElementRef; // use this if you want to insert inside a specific element in your template
constructor(
private renderer:Renderer2,
private el:ElementRef // use this if you want to insert into your template's root
) {
}
public ngAfterViewInit():void {
this.addNewButton();
}
public addNewButton():void {
const button = this.renderer.createElement('button');
const buttonText = this.renderer.createText('Click me');
this.renderer.appendChild(button, buttonText);
this.renderer.appendChild(this.insertTarget.nativeElement, button); // use this.el.nativeElement to insert into template root
this.renderer.listen(button, 'click', () => this.addNewButton());
}
}
template.ts
<p #inserttarget>
Some text
</p>
Here a working StackBlitz.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With