尝试在角度数据表中添加行单击事件,但不起作用

时间:2019-06-27 19:52:19

标签: angular typescript angular-datatables

我在我的数据表中实现了行单击事件。使用(http://l-lin.github.io/angular-datatables/#/advanced/row-click-event

中的教程和示例

我通过将表硬编码为HTML来运行示例来制作了一个模拟表。问题是,当我加载到网页中时,rowCallback函数似乎根本不起作用。据我所知,基本的数据表功能可以正常工作,排序,过滤搜索等。但是我什至无法获得单击以绑定到每个记录。几天来我一直在努力解决这个问题。谁能告诉我代码有什么问题吗?

<div class="col-md-12">
    <p class="homeText">{{homeText}}</p>
</div>
<blockquote>Please click on a row</blockquote>
<p class="text-danger">You clicked on: <strong>{{ message }}</strong></p>
<br />
<table datatable class="row-border hover">
    <thead>
      <tr>
        <th>ID</th>
        <th>First name</th>
        <th>Last name</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>1</td>
        <td>Foo</td>
        <td>Bar</td>
      </tr>
      <tr>
        <td>2</td>
        <td>Someone</td>
        <td>Youknow</td>
      </tr>
    </tbody>
  </table>
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  message = 'placeholder';
  public homeText: string;
  dtOptions: DataTables.Settings = {};

  constructor() { }

  someClickHandler(info: any): void {
    this.message = info.id + ' - ' + info.firstName;
  }

  ngOnInit() {
    this.homeText = "Welcome home";
    this.dtOptions = {
      ajax: 'data/data.json',
      columns: [{
        title: 'ID',
        data: 'id'
      }, {
        title: 'First name',
        data: 'firstName'
      }, {
        title: 'Last name',
        data: 'lastName'
      }],
      rowCallback: (row: Node, data: any[] | Object, index: number) => {
        const self = this;
        // Unbind first in order to avoid any duplicate handler
        // (see https://github.com/l-lin/angular-datatables/issues/87)
        $('td', row).unbind('click');
        $('td', row).bind('click', () => {
          self.someClickHandler(data);
        });
        return row;
      }
    };
  }
}

1 个答案:

答案 0 :(得分:0)

感谢sabithpocker指出的内容。我缺少js [dtOptions]="dtOptions",并且还包含js ajax: 'data/data.json',,这会导致此错误“ DataTables警告:表id = {id}-Ajax错误” https://datatables.net/manual/tech-notes/7