如何在 angular 2+ 中使用点击事件动态创建按钮

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

我想创建一个按钮 dynamically.I 使用 innerHtml 来执行此操作。 我可以创建 button.But 它的点击事件不起作用。 请告诉我如何解决这个问题?

这是我的 html 代码

<div  [innerHTML]="answerPanelContent"></div>

这是我的打字稿代码

 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');
    }

这是 stackblitz url:https://stackblitz.com/edit/angular-nka4w9

我强烈建议不要为此使用[innerHTML]。它不是为此目的而设计的,根本不是“angular 方式”。

使用 *ngFor

这是解决问题的最佳方法,也是“angular 方法”。

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

使用 Renderer2

如果*ngFor由于某些我们不知道的要求而无法解决您的问题,请仅使用此选项。

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>

这里是工作 StackBlitz.