angular-datatables icon indicating copy to clipboard operation
angular-datatables copied to clipboard

(click) not working on angular 2+ and 4+

Open tarzencar opened this issue 9 years ago • 30 comments

i have use angular 2.4 and i need to implement server side data table in my app so this purpose i have use this library but all functionality working except any angular event (ex. click) so any way to handle angular event in my app

i need to use button same as bellow

<button class="btn btn-danger" (click)="delete(user.id)">Delete

tarzencar avatar Mar 03 '17 10:03 tarzencar

I'm still trying to figure out how to do that... Sorry.

l-lin avatar Mar 03 '17 13:03 l-lin

BTW, for people searching how to do this, I solved doing this:

Create the button with a class:

    this.dtOptions = {
      ajax: 'api/admin/users',
      columns: [{
        title : 'Editar',
        defaultContent : `
        <button md-button class="mat-button edit-user">
          <md-icon class="material-icons mat-icon">add</md-icon>
        </button>`
      },
      ...

Listen to to click events for buttons of the assigned class, and do what you want:

  ngAfterViewInit(){
    this.datatableElement.dtInstance.then(dtInstance =>{
      dtInstance.on('click', '.edit-user', function(){
        let row_dom = $(this).closest('tr');
        let row = dtInstance.row(row_dom).data();
        
      })
    });
  }

you also have to declare $ variable in order to avoid compilation errors. declare const $;

joseahr avatar Mar 16 '17 18:03 joseahr

Good workaround. Unfortunately, you can't use Angular components with this solution... :cry:

l-lin avatar Mar 20 '17 17:03 l-lin

Any solution?

arthurfrancioni avatar May 11 '17 12:05 arthurfrancioni

@l-lin You close my thread (#1022), and it is ok, but you don't offer any solution to this thread

LexBel-co avatar May 17 '17 23:05 LexBel-co

@LexBel-co, because I still did not find any solution yet and no need to duplicate same issues.

l-lin avatar May 18 '17 07:05 l-lin

I created a workaround for this and is working great (so far). The code below very thorough or optimized, so let me know if you have questions.

First of all I create the angular template in the template like so:

<table datatable [dtOptions]="dtOptions" [dtTrigger]="dtTrigger">
<thead>
  <tr>
    <th>ID</th>
    <th>First name</th>
    <th>Last name</th>
    <th>Manage</th>
  </tr>
</thead>
<tbody>
  <tr *ngFor="let person of persons">
    <td>{{ person.id }}</td>
    <td>{{ person.firstName }}</td>
    <td>{{ person.lastName }}</td>
    <td><button (click)="remove(person)">remove</button></td>
  </tr>
</tbody>
</table>

Second, I set up a subscription to the results to update the template like so:

this.personsService.resultsChanged
      .subscribe(
        (results) => {
          this.persons = results.results;
          this.count = results.count;
        }
      );

Third, I setup the dtOptions to use ajax to trigger an update to my results EXCEPT always return empty data. Since my update will also update my subscription the angular template gets updated:

this.dtOptions = {
      ajax: (data: any, callback) => {
        let filter = {
          limit: 10,
          page: 1,
          q: undefined,
          sort: undefined
        };

        if (data) {
          if (data.columns && data.order && data.columns[data.order[0].column].name) {
            const dir = data.order[0].dir === 'asc' ? '' : '-';
            filter.sort = dir + data.columns[data.order[0].column].name;
          }
          if (data.search && data.search.value) {
            filter.q = data.search.value;
          }
          if (data.length) {
            filter.limit = data.length;
            if (data.start) {
              filter.page = Math.floor((data.start + 1) / data.length) + 1;
            }
          }
        }

        this.personsService.search(filter)
          .then(
            () => {
              callback({
                recordsTotal: this.count,
                recordsFiltered: this.count,
                data: []
              });
            });
      },
      serverSide: true,
      processing: true,
      pagingType: 'simple_numbers',
      columns: [
        {
          title: 'ID',
          orderable: false
        },
        { title: 'First Name' },
        {
          title: 'Last Name',
          orderable: false
        },
        {
          name: null,
          title: 'Manage',
          orderable: false,
          width: '80px',
          className: 'text-right'
        }
      ]
    };

Lastly, I have to hide the "no matches..." that DataTables generates by just using css to display none of that tr.

nbiles avatar Jun 28 '17 23:06 nbiles

@nbiles-av, what does your remove do? Can you share its content?

l-lin avatar Jun 30 '17 16:06 l-lin

@nbiles-av won't this cause problem with pagination, sorting, and search?

irman avatar Aug 23 '17 04:08 irman

@l-lin the remove calls our api to remove the item from the server then I remove it from the UI.

@irman it does not interfere with the pagination because it calls the ajax call on every change therefore it will update data. Does that make sense?

nbiles avatar Aug 23 '17 12:08 nbiles

I was able to get around this by using a little JS when using server side Ajax. editEntity and deleteEntity are TypeScript methods

In polyfills.ts add the following

declare global { interface Window { functions: any } }

Add the following in your ngOnInit() method

// binds component methods to javascript calls window.functions = window.functions || {}; window.functions.editEntity = this.editEntity.bind(this); window.functions.deleteEntity = this.deleteEntity.bind(this);

And then in your column definitions you can call the window functions

    {
        data: "id",
        render: (data, type, full) => {

            return '<a class="actions" onclick="functions.editEntity(' + data + ')" href="javascript:;">Edit</a>;

        }
    }

I also clean up in ngOnDestroy() window.functions = null;

pagner avatar Sep 14 '17 07:09 pagner

When using the AngularJS version, we could create a row callback and then execute this:

$compile(nRow)(vm.$scope);

Is it possible to do something similar but using the ComponentFactoryResolver instead (when using ajax for the data source)? So the options would look something like this:

{
  ajax: '/api/mydatasource',
  serverSide: true,
  processing: true,
  columns: [
    {
        title: 'Test', name: 'test', data: 'test',
        render: (data) => {
          return '<table-cell-component></table-cell-component>';
        }
    }
  ],
  rowCallback: (data, row, index) => {
    // Use the ComponentFactoryResolver to populate the <table-cell-component>?
  }
}

cjbland avatar Nov 17 '17 22:11 cjbland

So, is there any current development on angular-datatables toward possibility to insert angular components in columns.render()? that would make much easier further work with tables.

doink1985 avatar Dec 01 '17 08:12 doink1985

will this not work in your situation?

html:

<tbody>
                <tr *ngFor="let test of tests">
                    <td>{{ test.Author }}</td>
                    <td>
                        <a href="#" (click)="deleteTest($event, test )">
                            <i class="fa fa-trash-o fa-2x" aria-hidden="true" title="Delete Test"></i>
                        </a>
                    </td>
                </tr>
            </tbody>

TS:

deleteTest(e, test): void {
        e.preventDefault();

        // first unscribe any existing api subscription
        if (!!this.deleteSub) this.deleteSub.unsubscribe();

        // recall the server api with the latest data
        this.deleteSub = this.apiService.delete(`${this.urls.test}(${test.Id})`).subscribe(response => {

            this.dtElement.dtInstance.then((dtInstance: DataTables.Api) => {
                // Destroy the table first
                dtInstance.destroy();

                // load the test grid again with new data
                this.getTestGrid();
            });
        },
        (error) => {
            this.error = true;
            this.dtTrigger.next();
        });
    }

getTestGrid(): void {
        // first unscribe any existing api subscription
        if (!!this.apiSub) this.apiSub.unsubscribe();

        // load data
        this.apiSub = this.apiService.get(this.urls.test).subscribe(tests=> {
            this.tests = tests;
            // Calling the DT trigger to manually render the table
            this.dtTrigger.next();
            this.error = false;
        },
        (error) => {
            this.error = true;
            this.dtTrigger.next();
        });
    }

srikarshastry avatar Mar 16 '18 18:03 srikarshastry

@hotdog1987 several days ago I tried this approach and it works fine, except... it breaks reOrdering and colVis. the body of the table stays unchanged, while the header reacts as it has to - reOrders and hide .

doink1985 avatar Mar 17 '18 08:03 doink1985

Still no response.

pakcybershagufta avatar Apr 06 '18 09:04 pakcybershagufta

No solution....Sad

pakcybershagufta avatar Apr 06 '18 09:04 pakcybershagufta

I am facing same issue Recently i have upgraded my Angular/material and CDK dependencies.

now <button (click)="testing()">Click me!

while testing(){ console.log('testing'); } nothing appears in console.log. it's just glitched / bugged?

cyphercodes96 avatar Apr 18 '18 07:04 cyphercodes96

i have same problems in angular 5 i create action dynamically then (click) is not working.

DefaultDatatableDemo(data): void {

var options = {
  data: {
    type: 'local',
    source: data,
    pageSize: 10
  },
  layout: {
    theme: 'default',
    class: '',
    scroll: true,
    height: 350,
    footer: false
  },

  sortable: true,

  filterable: false,

  pagination: true,

  search: {
    input: $('#generalSearch')
  },

  // toolbar
  toolbar: {
    // toolbar items
    items: {
      // pagination
      pagination: {
        pageSizeSelect: [5, 10, 20, 30, 50, 100/*, -1*/] // display dropdown to select pagination size. -1 is used for "ALl" option
      }
    }
  },

  columns: [
    {
      field: 'UserId',
      title: '#',
      width: 40,
      selector: { class: 'm-checkbox--solid m-checkbox--brand' },
    },
    {
      field: 'id',
      title: '',
      width: 1,
      display: "none"
    },
    {
      field: "artist",
      title: "Artist",
      width: 100,
      responsive: { visible: 'lg' }
    },
    {
      field: "title",
      title: "Title",
      width: 95,
      responsive: { visible: 'lg' }
    },

    {
      field: "type",
      title: "Type",
      width: 75
    },

    {
      field: "size",
      title: "Size",
      width: 50,
      responsive: { visible: 'lg' }
    },
    {
      field: "category",
      title: "Category",
      width: 100,
      responsive: { visible: 'lg' }
    }
    , {
      field: "Actions",
      width: 190,
      title: "Actions",
      sortable: false,
      overflow: 'visible',
      template: function (row, index, datatable) {
      
        return '\<div style="cursor:pointer;"  (click)="playsong()" class="m-portlet__nav-link btn m-btn m-btn--hover-accent m-btn--icon m-btn--icon-only m-btn--pill" title="Play">\
						<i class="la la-play"></i>\
					</div>\
					<div style="cursor:pointer;"  id="m_datatable_edit_get" class="m-portlet__nav-link btn m-btn m-btn--hover-accent m-btn--icon m-btn--icon-only m-btn--pill" title="Edit" id="m_datatable_edit_get">\
						<i class="la la-edit"></i>\
					</div>\
        <div style="cursor:pointer;" class="m-portlet__nav-link btn m-btn m-btn--hover-accent m-btn--icon m-btn--icon-only m-btn--pill" title="QR Code">\
						<i class="la la-qrcode"></i>\
					</div>\
        <div style="cursor:pointer;" class="m-portlet__nav-link btn m-btn m-btn--hover-accent m-btn--icon m-btn--icon-only m-btn--pill" title="Statistic">\
						<i class="la la-bar-chart"></i>\
					</div>\
         <div style="cursor:pointer;"  id="m_datatable_delete_get" class="m-portlet__nav-link btn m-btn m-btn--hover-accent m-btn--icon m-btn--icon-only m-btn--pill" title="Delete">\
						<i class="la la-close"></i>\
					</div>\
        ';
      }
    }
  ]
};

bhavdip13 avatar Jun 01 '18 07:06 bhavdip13

Try single cotation

<button class="btn btn-danger"
(click)='delete(user.id)'>Delete

flaviofl avatar Jun 10 '18 06:06 flaviofl