Angular2-如何动态呈现带有单击事件的按钮 [英] Angular2 - How to render a button with click event dynamically

查看:259
本文介绍了Angular2-如何动态呈现带有单击事件的按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Angular2中有一个Web应用程序,其中正在使用SmartAdmin模板。
我的一个模板有一个数据表。

I have a Web App in Angular2, in which I am using the SmartAdmin template. One of my templates has a datatable.

对于表中的每个记录,我想要一个编辑按钮。

For each record in the table, I want to have an 'Edit' button.

这就是我的做法-

<sa-datatable #countryTable [options]="{
        ajax: 'assets/api/tables/datatables.filters.json',
        columns: [ {data: 'name'}, 
                   {data: 'position'}, 
                   {data: 'office'}, 
                   {data: 'age'}, 
                   {data: 'date'}, 
                   {data: 'salary'}, 
                   {defaultContent: '<button class=\'btn btn-default btn-xs edit-country-btn\' (click)=\'editClicked()\'>Edit</button>' } ] }"
       tableClass="table table-condenced table-striped table-bordered">
    .
    .
    .
</sa-datatable>

问题是按钮已渲染,但事件未绑定到该按钮。 (HTML照原样呈现,没有Angular2指令。)

The problem is that the button is rendered, but the event is not bound to it. (The HTML is rendered as it is, without Angular2 directives).

我尝试使用 render 呈现按钮。 defaultContent 的值。但这并不能正常工作。

I tried rendering the button using render instead of defaultContent. But that doesn't work as well.

编辑

我试图从DOM中获取 edit-country-btn 元素以将其绑定到事件,但是我似乎无法获取它们:

I tried to get the edit-country-btn elements from the DOM in order to bind them to the event, but I can't seem to fetch them:

在组件中-

@ViewChild('countryTable') public countryTable: any;

ngAfterViewInit() {
    var b = this.countryTable.el.nativeElement.querySelectorAll('button');
    console.log(b);
}

结果是按钮列表,但不是我想要的编辑按钮。

The result is a list of buttons, but not the edit buttons that I want.

推荐答案

您可以将click事件绑定到将为按钮元素激活的主体(或者如果希望将其激活)更具体地讲,您可以使用id,class等。)

You can bind a click event to the body which will be activated for button elements (or if you want it to be more specific you can use id, class etc.),

document.querySelector('body').addEventListener('click', (event)=> {
      if (event.target.tagName.toLowerCase() === 'button') {
         this.editClicked();
      }
    });

类似的示例: https://stackoverflow.com/a/42579935/5706293

这篇关于Angular2-如何动态呈现带有单击事件的按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆