我将 angular2 与 jQuery 一起使用,我创建了一个数据表,当我使用静态数据时一切都很好,但是一旦我做了一个循环 *ngFor 什么都不起作用(过滤,分页,搜索)
组件.html
<table id="dtb" class="table table-striped table-no-bordered table-hover" cellspacing="0" width="100%"
style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Date</th>
<th class="disabled-sorting text-right">Actions</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th class="text-right">Actions</th>
</tr>
</tfoot>
<tbody>
<tr *ngFor="let data of datas">
<td>{{data.Name}}</td>
<td>{{data.Position}}</td>
<td>{{data.Office}}</td>
<td>{{data.Age}}</td>
<td>{{data.Date}}</td>
<td class="text-right">
<a href="#" class="btn btn-simple btn-info btn-icon like"><i class="material-icons">favorite</i></a>
<a href="#" class="btn btn-simple btn-warning btn-icon edit"><i class="material-icons">dvr</i></a>
<a href="#" class="btn btn-simple btn-danger btn-icon remove"><i class="material-icons">close</i></a>
</td>
</tr>
</tbody>
</table>
组件.ts
import {Component, OnInit, ElementRef} from '@angular/core';
import {TableData} from './table-data';
declare var $:any;
@Component({
templateUrl: 'Home.component.html'
})
export class HomeComponent implements OnInit {
datas: Array<any> = TableData;
constructor(private _elRef: ElementRef) {}
ngOnInit() {
jQuery(this._elRef.nativeElement).find('#dtb').DataTable();
}
}
有什么帮助吗?谢谢大家
最佳答案
将数据传递到数据表并让它负责渲染记录。像这样:
在你的 component.html 中:
<table id="dtb" tableClass="table table-condenced table-striped table-bordered">
<thead>
<tr>
<th data-class="expand">Name</th>
<th>Position</th>
<th></th>
</tr>
</thead>
</table>
在你的 component.ts 中:
let options = {
data: this.datas,
columns: [
{ data: 'Name' },
{ data: 'Position' },
{
render: function (a, b) {
return '<a href="#" class="btn btn-simple btn-info btn-icon like my-datatable-btn" id="' + a.Id + '"><i class="material-icons">favorite</i></a>';
}
}]
}
jQuery(this._elRef.nativeElement).find('#dtb').DataTable(options);
如果您想将“angular2 事件或属性”(例如(单击)或 [routerLink])绑定(bind)到数据表中的超链接,则它将不起作用,因为此 HTML 是“动态”生成的。为此,您还必须执行以下操作:
this._elRef.nativeElement.addEventListener('click', (event) => {
var className = $(event.target).attr('class');
if(className.indexOf('my-datatable-btn') > -1) { //check if the target of the click event is what you want.
//Call your onclick handler here.
}
});
除了像您的情况一样传递数据
之外,还有other useful options您可以将其传递到数据表。
关于jquery - Angular 2、jQuery、*ngFor 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44022753/