如何在Angular 6中动态创建的按钮上的click事件上绑定?

时间:2018-09-06 12:42:32

标签: javascript angular angular6

我正在尝试创建带有onclick事件的动态按钮。 showname()在相同的Component.ts上定义了。但是点击按钮没有任何反应

  

Component.ts

createtooltip() {
  this.tooltip = document.createElement('div');
  this.tooltip.style.cssText =
    'position:absolute; background:black; color:white; padding:4px;z-index:10000;' +
    'border-radius:2px; font-size:12px;box-shadow:3px 3px 3px rgba(0,0,0,.4);' +
    'opacity:0;transition:opacity 0.3s';
  this.tooltip.innerHTML = '<button id="popup" (click)="showname()" >Copy!</button>';
  document.body.appendChild(this.tooltip);
}

showname() {
  console.log("Hi User");
}

有人可以帮助我找到解决方案吗?

4 个答案:

答案 0 :(得分:1)

您将无处访问文档对象。

因此,您不应该使用document函数来进行DOM操作。所有这些DOM操作都应仅使用Rendere2完成。如果要在DOM上访问任何内容,则应使用@ViewChild

这是一个例子:

import { Component, Renderer2, ElementRef, ViewChild } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name = 'Angular';
  @ViewChild('tooltip') tooltip: ElementRef;

  constructor(private renderer: Renderer2) {}

  createtooltip() {
    this.renderer.setAttribute(this.tooltip.nativeElement, 'class', 'my-button');

    const button = this.renderer.createElement('button');
    this.renderer.setProperty(button, 'id', 'popup');
    this.renderer.setProperty(button, 'innerText', 'Copy');
    this.renderer.listen(button, 'click', (event) => {
      this.showname();
    })

    this.renderer.appendChild(this.tooltip.nativeElement, button);
  }

  showname() {
    console.log("Hi User");
  }

}

在模板中:

<button (click)="createtooltip()">Create Tooltip</button>

<div #tooltip>

</div>

在CSS中:

p {
  font-family: Lato;
}

.my-button {
  position:absolute;
  background:black;
  color:white;
  padding:4px;
  z-index:10000;
  border-radius:2px;
  font-size:12px;
  box-shadow:3px 3px 3px rgba(0,0,0,.4);
  opacity:0;
  transition:opacity 1s linear;
}

这里是Sample StackBlitz供您参考。

答案 1 :(得分:0)

angular不会编译动态创建的HTML元素。您必须像这样使用 ng-template

<ng-template #myTemplate>
    <div styles="...">
       <button id="popup" (click)="showname()" >Copy!</button>
    </div>
</ng-template>

答案 2 :(得分:0)

最好使用像*ngFor*ngIf这样的指令来创建按钮,而不要像使用Jquery那样创建元素。

这是由于Angular的特性所致,它比简单的javascript优先考虑并简化了指令的使用。

为此,您可以:

HTML:

<button id="popup" (click)="showname()" *ngIf='elements.showNameButton==true' >Copy!</button>

** TS:**

elements={
 showNameButton:false
}

createtooltip(){
 this.elements.showNameButton =true;
}

showname() {
  console.log("Hi User");
}

答案 3 :(得分:0)

我用另一种方法解决了这个问题

<a ngFor="let link of links" (click)="actions[link]()">Click</a>

` 动作:任何= {

link1: () => this.func1(),
link2: () => this.func2()

} `