无法读取Angular 7中未定义的属性“ nativeElement”

时间:2019-06-28 16:18:27

标签: angular

我想在我的有角度的应用程序中实现数据表,但是它显示了类似Cannot read property 'nativeElement' of undefined的错误,我在Google上搜索了几次,但是找不到任何合适的解决方案,所以我该如何解决这个问题。

安装所有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">

4 个答案:

答案 0 :(得分:0)

这个问题

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

答案 1 :(得分:0)

@ViewChild钩子 [docs]之前设置

AfterViewInit查询。尝试这种方式;

export class AppComponent implements AfterViewInit {
  @ViewChild("dataTable", { static: true }) table: any;

  ngAfterViewInit() {
    console.log(this.table.nativeElement);
  }
}

答案 2 :(得分:0)

@ViewChild('dataTable') table: ElementRef;

ngAfterViewInit(): void {
  if (!this.table) return;
    this.dataTable = $(this.table.nativeElement);
    this.dataTable.DataTable();
}

使用条件来避免表为空的错误。

答案 3 :(得分:0)

通常,该错误表示您正在访问其“ nativeElement”属性的对象是未定义的。

在此示例中,ViewChild并未在调用table的{​​{3}}中设置ngOnInit()属性。您需要使用ngAfterViewInit()ngAfterViewChecked()

ngAfterViewInit(): void 
{
    this.dataTable = $(this.table.nativeElement);
    this.dataTable.DataTable();
}

对于这种特殊情况,一种更好的处理方法是在组件外部创建一个可以执行此操作的指令。

更好的方法是停止使用jquery,因为angular希望拥有dom。例如,如果您的表数据更改,jquery将不同步,可能会导致问题。查看component lifecycle ...