在引入datatables.net之前,将Angular的ngFor重命名为其他变量名,避免变量名冲突。
使用jQuery选择器将数据插入datatables.net中,而不是在HTML模板中使用ngFor。
示例代码:
//app.component.ts import { Component, OnInit, ViewChild } from '@angular/core'; declare var $: any;
@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { titles = ['Title 1', 'Title 2', 'Title 3']; data = [ { value1: 'Value 1-1', value2: 'Value 1-2', value3: 'Value 1-3' }, { value1: 'Value 2-1', value2: 'Value 2-2', value3: 'Value 2-3' }, { value1: 'Value 3-1', value2: 'Value 3-2', value3: 'Value 3-3' } ];
@ViewChild('table') table;
ngOnInit() { const table = $(this.table.nativeElement); table.DataTable({ data: this.data, columns: [ { data: 'value1', title: this.titles[0] }, { data: 'value2', title: this.titles[1] }, { data: 'value3', title: this.titles[2] } ] }); } }
//app.component.html