Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create button dynamically with click event in angular 2+

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

like image 984
DevAra Avatar asked Jun 13 '26 09:06

DevAra


1 Answers

I strongly recommend not using [innerHTML] for this. It is not meant for this purpose and not the "angular way" at all.

Using *ngFor

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

Using Renderer2

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.

like image 177
pascalpuetz Avatar answered Jun 15 '26 01:06

pascalpuetz