如何创建通用服务以按角度整合所有页面的jQuery数据表 [英] How to create a common service to integrate jQuery datatable for all pages in angular
问题描述
我想创建公共服务以在多个页面上集成jQuery数据表(带有导出按钮).
I want to create common service to integrate jQuery datatables(with export buttons) on multiple pages.
我已经安装了jquery并为jquery键入内容. tsconfig types数组中还包含了jquery.
I have installed jquery and typings for jquery. Also have included jquery in tsconfig types array.
"types": [
"jquery"
]
索引页上包含数据表所需的CDN.
Included required cdn(s) for datatable on index page.
在types.d.ts中添加了一个接口JQuery:
Added an interface JQuery in typings.d.ts :
interface JQuery {
<dataTable>(options?: any): any;
}
Angular服务:
ApplyDatatable() {
$(".mydataTable").dataTable({
"pagingType": "full_numbers",
"iDisplayLength": 10,
bJQueryUI: true,
"aLengthMenu": [[-1, 10, 20, 50, 100], ["All", 10, 20, 50, 100]],
select: true,
"aaSorting": [],
"aoColumnDefs": [
{
'bSortable': false,
'aTargets': ['disableSorting', 'noExport']
}],
buttons: [
{
extend: 'collection',
text: 'Export',
buttons: [
//'copy',
{
extend: 'copyHtml5',
exportOptions: {
columns: ':visible',
columns: "thead th:not(.noExport)"
}
},
{
extend: 'csvHtml5',
exportOptions: {
columns: ':visible',
columns: "thead th:not(.noExport)"
}
}
],
dom: 'lfBrtip',
});
}
遇到错误:
jquery__WEBPACK_IMPORTED_MODULE_6 __(...).dataTable不是一个函数(在浏览器控制台上).
jquery__WEBPACK_IMPORTED_MODULE_6__(...).dataTable is not a function (on browser console).
在编译项目时出现错误类型'JQuery'不存在属性'dataTable'
while compiling project getting the error Property 'dataTable' does not exist on type 'JQuery'
推荐答案
使用jQuery插件时,应创建一个Angular组件作为数据表的包装.然后,您可以在 component 呈现后调用jQuery插件.
When using a jQuery plugin, you should create an Angular component as a wrapper for the datatable. Then you can call the jQuery plugin after the component renders.
import { Component, AfterViewInit } from '@angular/core';
import 'jquery';
@Component({
selector: 'app-datatables',
...
})
export class AppDatatables implements AfterViewInit {
ngAfterViewInit() {
($(".mydataTable") as any).dataTable({
...
});
}
}
组件模板:
<div class="mydataTable"></div>
因为您已经在另一个问题中问过如何为每个新页面呈现此视图,现在也解决了该问题,因为每次加载/创建新页面时都会重新添加该组件.
Since you already asked in another question how to render this for every new page(view), that problem is solved now as well, since the component will be re-added every time a new page is loaded/created.
这篇关于如何创建通用服务以按角度整合所有页面的jQuery数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!