我想在我的角度应用程序中实现数据表,但它显示了一个错误,如
Cannot read property 'nativeElement' of undefined
我用谷歌搜索了几次,但我找不到任何合适的解决方案,所以我该如何解决这个问题。
安装所有npm
npm install jquery --save
npm install datatables.net --save
npm install datatables.net-dt --save
npm install @types/jquery --save-dev
npm install @types/datatables.net --save-dev
在 angular.json 文件中添加这些代码
"styles": [
"node_modules/datatables.net-dt/css/jquery.dataTables.css"
],
"scripts": [
"node_modules/jquery/dist/jquery.js",
"node_modules/datatables.net/js/jquery.dataTables.js"
]
这是我的代码
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
@ViewChild('dataTable') table;
dataTable: any;
ngOnInit(): void
{
this.dataTable = $(this.table.nativeElement);
this.dataTable.DataTable();
}
在我的桌子里面
<table #dataTable class="table table-bordered table-striped">
@ViewChild
查询在 AfterViewInit
钩子 [文档] 之前设置。试试这个方法;
export class AppComponent implements AfterViewInit {
@ViewChild("dataTable", { static: true }) table: any;
ngAfterViewInit() {
console.log(this.table.nativeElement);
}
}
对于这个问题
import { Component, AfterViewInit, ViewChild, ElementRef } from '@angular/core';
@ViewChild('dataTable', {static: false}) table: ElementRef;
ngAfterViewInit(){
this.dataTable = $(this.table.nativeElement);
this.dataTable.DataTable();
}
但我建议你不要将 Jquery 与 Angular 一起使用,而是使用 mat table
@ViewChild('dataTable') table: ElementRef;
ngAfterViewInit(): void {
if (!this.table) return;
this.dataTable = $(this.table.nativeElement);
this.dataTable.DataTable();
}
如果表为空,请使用条件以避免错误。
一般来说,该错误意味着您正在访问的“nativeElement”属性的对象未定义。
在此示例中,ViewChild 不会在调用
table
的 组件生命周期 中设置您的 ngOnInit()
属性。您需要使用 ngAfterViewInit()
或 ngAfterViewChecked()
:
ngAfterViewInit(): void
{
this.dataTable = $(this.table.nativeElement);
this.dataTable.DataTable();
}
对于这种特殊情况,更好的处理方法是在组件外部创建一个指令来执行此操作。
更好的方法是停止使用 jquery,因为 Angular 想要拥有 dom。例如,如果您的表数据发生更改,jquery 将失去同步,并且可能会导致问题。查看角材料表...
如果您尝试获取对材料表的元素引用,也可能会发生这种情况;在这种情况下,默认情况下,
ViewChild
装饰器不会返回ElementRef
,而是返回MatTable
类。
如果您不想要
MatTable
课程,则必须通过 { read: ElementRef }
来明确标记您对 ElementRef
感兴趣。
在您的模板中:
<table #table mat-table [dataSource]="dataSource">
<!-- ... -->
</table>
在您的组件中:
@ViewChild('table', { read: ElementRef }) public tableElementRef: ElementRef<HTMLTableElement>;
现在您可以在视图正常初始化后访问
ElementRef
:
public ngAfterViewInit(): void {
const tableElement: HTMLTableElement = this.tableElementRef.nativeElement;
}