1

I've added Angular 2 to an older application which primarily was built using jQuery + plugins. I'm trying to use jQuery DataTables inside of a Component. I can get it to load the table just fine. The problem is that I have a cell template that has NG2 event listeners. In Angular 1 I could use the $compile service to register them to the scope, but that's gone away. This is how the DataTable is created in code, including the cell template:

$('#myTable').DataTable({
 data: data,
 columns: [
 {
 data: 'Dimension'
 , render: function (data: any, type: any, obj: any, tbl: any) {
 //return data;
 var template =
 `<div class="container-fluid">
 <div class="row text-left" style="">
 <div>
 <div class="col-md-12">
 <i class="glyphicon glyphicon-plus" (click)="showChildren()"></i>&nbsp;
 ${obj.Name}
 &nbsp;&nbsp;<i class="glyphicon glyphicon-plus-sign" (click)="addNew()"></i>
 </div>
 </div>
 </div>
 </div>`;
 return template;
 }
 }
 ]
 });
});

The (click) event listeners just get rendered as html and do nothing. How do I get them to work?

asked Dec 1, 2016 at 20:59

1 Answer 1

2

You could render the data bound items first as hidden data blocks, then match them to the palceholder templates through jQuery, like below:

HTML:

<div class="container-fluid source-data" attr.data-name="{{obj.Name}}" 
 *ngFor="obj in objArray; trackBy: obj.Name" style="display: none;">
 <div class="row text-left" style="">
 <div>
 <div class="col-md-12">
 <i class="glyphicon glyphicon-plus" (click)="showChildren()"></i>&nbsp;
 {{obj.Name}}
 &nbsp;&nbsp;<i class="glyphicon glyphicon-plus-sign" (click)="addNew()"></i>
 </div>
 </div>
</div>

Javascript:

// Initialize jQuery Data Table
$('#myTable').DataTable({
 data: data,
 columns: [{
 data: 'Dimension', 
 render: function (data: any, type: any, obj: any, tbl: any) {
 return `<div id="divTemplate${obj.Name}"></div>`;
 }
 }
 ]
});
// Transfer each DOM data block to the data table templates
$('.source-data[data-name]').each(function () {
 var id = $(this).attr('data-name');
 var html = $(this).attr('data-name').html();
 $('#divTemplate' + id).html(html);
});
answered Dec 1, 2016 at 22:36
Sign up to request clarification or add additional context in comments.

2 Comments

While this works for moving the html into the DataTable, the events do not work in the DataTable.
Instead of the last lines starting with var html = $(this).attr..., try instead $(this).attr('data-name').children().detach().appendTo($('#divTemplate' + id));

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.