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> 
 ${obj.Name}
   <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?
1 Answer 1
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> 
 {{obj.Name}}
   <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);
});
2 Comments
Explore related questions
See similar questions with these tags.