Angular5:如何将异步加载的数据中的事件绑定到数据表

时间:2018-02-08 09:52:22

标签: angular datatables event-binding

通过包含编辑和删除按钮的ajax加载表数据, 现在,当我尝试通过事件绑定访问特定按钮时,它无法正常工作

这是html部分

<div class="widget-body no-padding">
<sa-datatable [options]="tableData" paginationLength="true" tableClass="table table-striped table-bordered table-hover" width="100%">
    <thead>
        <tr>
            <th data-hide="phone"> ID </th>
            <th data-class="expand"> Name </th>
            <th data-hide="phone,tablet"> Email </th>
            <th data-hide="phone,tablet"> Role </th>
            <th data-hide="phone,tablet"> join Date </th>
            <th data-hide="phone,tablet"> Action </th>
        </tr>
    </thead>
</sa-datatable>

并在组件中通过ajax加载数据

tableData = {
ajax: (data, callback, settings) => {
  this.usersService.getUsers(0).subscribe(data => {
    if(data.success){
        callback({
          aaData: data.data
        });
    } else {
      alert(data.msg);
    }
  },
  error => {
      alert('Internal server error..check database connection.');
  });
},
columns: [ 
    { 
      render: function (data, type, row, meta) {
          return meta.row + meta.settings._iDisplayStart + 1;
      }
    },
    {
      data: function (name) { return  name.firstname+ ' ' + name.lastname; }
    }, 
    {data: 'email'},
    {data: 'user_role'}, 
    {data: 'created_at'},
    {          
      render: function (data, type, row) {
        return `<ul class="demo-btns">\
                  <li> <span (click)="edit()" class="btn btn-primary btn-xs"><i class="fa fa-gear"></i> Edit</span></li>\
                    <li> <span class="btn btn-danger btn-xs"><i class="fa fa-gear"></i> Delete</span></li>\
                </ul>`;
      }
    }
],
buttons: [
    'copy', 'pdf', 'print'
]};

edit(){
console.log('Clicked..');}

当我通过ajax加载数据时,看起来似乎没有创建dom元素,这就是它不发出任何事件的原因。有谁能请让我知道如何以任何其他方式点击按钮来听取事件。

3 个答案:

答案 0 :(得分:0)

可以通过收听事件来实现

    tableData = {
    ajax: (data, callback, settings) => {
      this.usersService.getUsers(0).subscribe(data => {
        if(data.success){
            callback({
              aaData: data.data
            });
        } else {
          alert(data.msg);
        }
      },
      error => {
          alert('Internal server error..check database connection.');
      });
    },
    columns: [ 
        { 
          render: function (data, type, row, meta) {
              return meta.row + meta.settings._iDisplayStart + 1;
          }
        },
        {
          data: function (name) { return  name.firstname+ ' ' + name.lastname; }
        }, 
        {data: 'email'},
        {data: 'user_role'}, 
        {data: 'created_at'},
        {          
          render: function (data, type, row) {
            return `<button type="button" class="btn btn-warning btn-xs edit" data-element-id="${row._id}"><i class="fa fa-pencil-square-o"></i> Edit</button>`;
          }
        }
    ],
    buttons: [
        'copy', 'pdf', 'print'
    ]

      };

      ngAfterViewChecked() {

    document.querySelector('body').addEventListener('click', (event)=> {
        let target = <Element>event.target;// Cast EventTarget into an Element
        if (target.tagName.toLowerCase() === 'button' && $(target).hasClass('btn-warning')) {
            this.user_edit(target.getAttribute('data-element-id'));
        }   
    });

  }

      user_edit(userId){
        console.log("user edit:", userId);
      }

答案 1 :(得分:0)

使用angular click指令有效地监听和呈现DOM。 https://docs.angularjs.org/api/ng/directive/ngClick

答案 2 :(得分:0)

最后,我在使用addEventListner进行一些更改之后找到了工作代码,这里的代码对某人有用。

tableData: any;
 ngOnInit() {  
    tableData = {
              ajax: (data, callback, settings) => {
                this.usersService.getUsers(0).subscribe(data => {
                  if(data.success){
                      callback({
                        aaData: data.data

                      });
                  } else {
                    alert(data.msg);
                  }
                },
                error => {
                    alert('Internal server error..check database connection.');
                });
              },
              columns: [ 
                  { 
                    render: function (data, type, row, meta) {
                        return meta.row + meta.settings._iDisplayStart + 1;
                    }
                  },
                  {
                    data: function (name) { return  name.firstname+ ' ' + name.lastname; }
                  }, 
                  {data: 'email'},
                  {data: 'user_role'}, 
                  {data: 'created_at'},
                  {          
                    render: function (data, type, row) {
                      return `<button type="button" class="btn btn-warning btn-xs edit" data-element-id="${row._id}">
                      <i class="fa fa-pencil-square-o"></i> Edit</button>`;
                    }
                  }
              ],
              buttons: [
                  'copy', 'pdf', 'print'
              ]
            };

            document.querySelector('body').addEventListener('click', (event)=> {
                let target = <Element>event.target; // Cast EventTarget into an Element
                if (target.tagName.toLowerCase() === 'button' && $(target).hasClass('edit')) {
                  this.user_edit(target.getAttribute('data-element-id'));          
                }   
            });

              user_edit(user_id){
                console.log("user edit:" +user_id);
                // Here goes the edit login
              }
}