question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Angular 4 + DataTables = Cannot read property 'mData' of undefined at HTMLTableCellElement.eval

See original GitHub issue

What versions you are using?

- node version: v6.11.3
- npm version: 5.2.0
- angular version: 4.3.3
- jquery version: ^3.1.1
- datatables.net: ^1.10.16
- datatables.net-dt: ^1.10.16
- angular-datatables version: ^4.4.0
- angular-cli version: 1.2.7
- @types/datatables.net: ^1.10.6
- @types/jquery: ^3.2.15

What’s the problem?

Recently in my private project I wanted to implement the Angular Datatable, however, it does not work, I followed the steps of ‘https://l-lin.github.io/angular-datatables/#/getting-started’ and tried to use the settings of the ‘https://l-lin.github.io/angular-datatables/#/basic/zero-config’ example. But the following error occurs:

ERROR TypeError: Cannot read property ‘mData’ of undefined at HTMLTableCellElement.eval (eval at webpackJsonp…/…/…/…/script-loader/addScript.js.module.exports (addScript.js:20), <anonymous>:1172:15) at Function.each (eval at webpackJsonp…/…/…/…/script-loader/addScript.js.module.exports (addScript.js:20), <anonymous>:2:2715) at r.fn.init.each (eval at webpackJsonp…/…/…/…/script-loader/addScript.js.module.exports (addScript.js:20), <anonymous>:2:1003) at HTMLTableElement.eval (eval at webpackJsonp…/…/…/…/script-loader/addScript.js.module.exports (addScript.js:20), <anonymous>:1169:39) at Function.each (eval at webpackJsonp…/…/…/…/script-loader/addScript.js.module.exports (addScript.js:20), <anonymous>:2:2715) at r.fn.init.each (eval at webpackJsonp…/…/…/…/script-loader/addScript.js.module.exports (addScript.js:20), <anonymous>:2:1003) at r.fn.init.DataTable [as dataTable] (eval at webpackJsonp…/…/…/…/script-loader/addScript.js.module.exports (addScript.js:20), <anonymous>:869:8) at r.fn.init.$.fn.DataTable (eval at webpackJsonp…/…/…/…/script-loader/addScript.js.module.exports (addScript.js:20), <anonymous>:15069:18) at angular-datatables.directive.js:38 at ZoneDelegate.webpackJsonp…/…/…/…/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:424)

Can you share your code?

component.html:

<table datatable [dtOptions]="dtOptions" [dtTrigger]="dtTrigger" class="row-border hover">
      <thead>
        <tr>
          <th>Solicitante</th>
          <th>Descrição</th>
          <th>Data solicitação</th>
          <th>Tipo FST</th>
         <th>Situação integração</th>
         <th class="text-right"></th>
       </tr>
     </thead>
      <tbody>
         <tr *ngFor="let solicitacao of solicitacoes">
          <td>{{solicitacao.user_solicitante}}</td>
          <td>{{solicitacao.solicitacao}}</td>
          <td>{{solicitacao.data_solicitacao | date:'dd/MM/yyyy'}}</td>
          <td>{{solicitacao.DescTipo_solicitacao}}</td>
         <td>{{solicitacao.status}}</td>
          <td class="text">
            <button class="btn btn-link btn-sm" [routerLink]="['/fst/solicitacao', solicitacao._id, 'view']"><i class="fa fa-eye"></i></button>
          </td>
          <td class="text">
            <button class="btn btn-info btn-sm" [routerLink]="['/fst/solicitacao', solicitacao._id]" [disabled]="solicitacao?.status == 'Em processamento'"><i class="fa fa-pencil"></i></button>
         </td>
          <td class="text">
            <button class="btn btn-danger btn-sm" mwlConfirmationPopover [title]="title" [message]="message" placement="left" [confirmText]="confirmText" [cancelText]="cancelText" (confirm)="removerSolicitacao(solicitacao)" (cancelar)="cancelClicked = true" [disabled]="solicitacao?.status == 'Em processamento'">
                   <i class="fa fa-trash"></i></button>
          </td>
         <td class="text">
            <button class="btn btn-primary btn-sm" (click)="enviarFtp(solicitacao)" [disabled]="solicitacao?.status == 'Em processamento'"><i class="fa fa-paper-plane"></i></button>
         </td>
        </tr>
      </tbody>
    </table>

component.ts:

 import { Component, OnInit } from '@angular/core';
 import {FormBuilder, FormControl, FormGroup, FormsModule, ReactiveFormsModule} from '@angular/forms'
 import {Router, ActivatedRoute} from '@angular/router'
 import {Subject} from 'rxjs/Rx'

 import {Solicitacao} from './solicitacao/solicitacao.model'
 import {SolicitacoesService} from './solicitacoes.service'

 import {Observable} from 'rxjs/Observable'
 import 'rxjs/add/operator/switchMap'
 import 'rxjs/add/operator/do'
 import 'rxjs/add/operator/map'
 import 'rxjs/add/operator/debounceTime'
 import 'rxjs/add/operator/distinctUntilChanged'
 import 'rxjs/add/operator/catch'
 import 'rxjs/add/observable/from'
 
 @Component({
   selector: 'ses-solicitacoes',
   templateUrl: './solicitacoes.component.html'
 })
 
 export class SolicitacoesComponent implements OnInit {
 
  dtOptions: DataTables.Settings = {}
  dtTrigger: Subject<any> = new Subject<any>()
  solicitacoes: Solicitacao[] = []
   title: string = 'Excluir solicitação!';
   message: string = 'Você está prestes a excluir uma solicitação, deseja prosseguir?';
   confirmClicked: boolean = false;
   cancelClicked: boolean = false;
   confirmText: string = 'Confirmar'
   cancelText: string = 'Cancelar'
 
   constructor(private restaurantsService : SolicitacoesService,
               private router: Router) { }
 
   ngOnInit() {
     this.dtOptions = {
      searching: false,
      lengthChange: false
    }
     this.restaurantsService.solicitacoes()
       .subscribe(solicitacoes => {
         this.solicitacoes = solicitacoes
         this.dtTrigger.next();
       })
   }

   removerSolicitacao(solicitacao: Solicitacao){
     let id : string = solicitacao._id
    this.restaurantsService.removeSolicitacaobyId(id)
      .subscribe((solicitacaoId: any) => {
         this.ngOnInit()
     })
   }

   enviarFtp(solicitacao: Solicitacao){
     let id : string = solicitacao._id
     this.restaurantsService.enviaSolicitacaoFtp(id)
      .subscribe((solicitacaoId: any) => {
         this.ngOnInit()
     })
   }
 }

service.ts:

import {Injectable} from '@angular/core'
import {HttpClient, HttpParams} from '@angular/common/http';
import {SES_API} from "../app.api"
import {Solicitacao} from "./solicitacao/solicitacao.model"
import {Observable} from 'rxjs/Observable'
import 'rxjs/add/operator/map'
import 'rxjs/add/operator/catch'
import {ApplicationErrorHandler} from '../app.error-handler'
import {UserService} from '../security/users/users.service'

@Injectable()
export class SolicitacoesService {
  constructor(private http: HttpClient,
              private userService: UserService) {}

  solicitacoes(search?: string): Observable<Solicitacao[]> {
    let params: HttpParams = undefined
    if(search){
      params = new HttpParams().set('q', search)
    }
    return this.http.get<Solicitacao[]>(`${SES_API}/solicitacoes`, {params: params})
  }
}

appcomponent.module.ts:

 import {NgModule, ModuleWithProviders} from '@angular/core'
 import {HTTP_INTERCEPTORS} from '@angular/common/http'
 import {RouterModule, Routes} from '@angular/router'
 import {ConfirmationPopoverModule} from 'angular-confirmation-popover';
 import {DataTablesModule} from 'angular-datatables';
 import {SharedModule} from '../shared/shared.module'
 
 import { SolicitacoesComponent } from './solicitacoes.component';
 import { SolicitacaoComponent } from './solicitacao/solicitacao.component';
 import { ArquivosAnexadosComponent } from './arquivos-anexados/arquivos-anexados.component';
 import { ConsultafstComponent } from '../consultafst/consultafst.component';
 import { SolicitacaoDiversasComponent } from './solicitacao/solicitacao-diversas/solicitacao-diversas.component';
 import { SolicitacaoEtiquetaComponent } from './solicitacao/solicitacao-etiqueta/solicitacao-etiqueta.component';
import { SolicitacaoRelatorioComponent } from './solicitacao/solicitacao-relatorio/solicitacao-relatorio.component';
 
 const ROUTES: Routes = [
   {path:'', redirectTo:'fst', pathMatch: 'full'},
  {path: 'solicitacoes', component: SolicitacoesComponent},
  {path: 'solicitacao', component: SolicitacaoComponent},
   {path: 'solicitacao/:id', component: SolicitacaoComponent},
  {path: 'solicitacao/:id/:view', component: SolicitacaoComponent},
   {path: 'consultaFst', component: ConsultafstComponent},
 ]
 
 @NgModule({
   declarations: [SolicitacoesComponent,
                 SolicitacaoComponent,
                ArquivosAnexadosComponent,
                 ConsultafstComponent,
                 SolicitacaoDiversasComponent,
                SolicitacaoEtiquetaComponent,
                SolicitacaoRelatorioComponent],
   imports: [SharedModule,
           DataTablesModule,
             RouterModule.forChild(ROUTES),
          ConfirmationPopoverModule.forRoot({confirmButtonType: 'danger'})]
 })

 export class SolicitacoesModule {}

angular-cli.json:

 {
   "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
   "project": {
     "version": "1.0.0",
     "name": "ses-solicitacao"
   },
   "apps": [
     {
       "root": "src",
       "outDir": "dist",
       "assets": [
         "assets",
         "microicon.ico"
       ],
       "index": "index.html",
       "main": "main.ts",
       "polyfills": "polyfills.ts",
       "test": "test.ts",
       "tsconfig": "tsconfig.json",
       "testTsconfig": "tsconfig.spec.json",
       "prefix": "ses",
       "mobile": false,
       "styles": [
         "../node_modules/datatables.net-dt/css/jquery.dataTables.css",
         "../node_modules/font-awesome/css/font-awesome.min.css",
         "../node_modules/admin-lte/bootstrap/css/bootstrap.min.css",
         "../node_modules/admin-lte/dist/css/AdminLTE.min.css",
         "../node_modules/admin-lte/dist/css/skins/skin-blue.min.css",
         "styles.css"
       ],
       "scripts": [
         "../node_modules/jquery/dist/jquery.js",
         "../node_modules/jquery/dist/jquery.min.js",
         "../node_modules/datatables.net/js/jquery.dataTables.js",
         "../node_modules/admin-lte/bootstrap/js/bootstrap.min.js",
         "../node_modules/admin-lte/dist/js/app.min.js"
       ],
       "environmentSource": "environments/environment.ts",
       "environments": {
         "dev": "environments/environment.ts",
         "prod": "environments/environment.prod.ts"
       }
     }
   ],
   "addons": [],
   "packages": [],
   "e2e": {
     "protractor": {
       "config": "./protractor.conf.js"
     }
   },
     "lint": [
     {
       "project": "src/tsconfig.app.json"
     },
     {
       "project": "src/tsconfig.spec.json"
     },
     {
       "project": "e2e/tsconfig.e2e.json"
     }
   ],
   "test": {
     "karma": {
       "config": "./karma.conf.js"
     }
   },
   "defaults": {
     "styleExt": "css",
     "prefixInterfaces": false,
     "inline": {
       "style": false,
       "template": false
     },
     "spec": {
       "class": false,
       "component": true,
       "directive": true,
       "module": false,
       "pipe": true,
       "service": true
     }
   }
 }

tsconfig.json:

{
 "compilerOptions": {
   "sourceMap": true,
   "declaration": false,
   "moduleResolution": "node",
   "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [
     "es2016",
      "dom"
     ],
   "outDir": "../out-tsc/app",
    "target": "es5",
    "module": "es2016",
    "baseUrl": "",
     "types": [],
    "typeRoots": [
       "../node_modules/@types"
    ],
   "paths": {
      "@angular/*": [
        "../node_modules/@angular/*"
       ]
     }
   },
  "exclude": [
     "test.ts",
     "**/*.spec.ts"
  ]
 }

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:7 (1 by maintainers)

github_iconTop GitHub Comments

1reaction
jsilveira2commented, Oct 31, 2017

It did not work for me. Even with ‘setTimeout’ the problem remains the same stating that: ERROR TypeError: Cannot read property ‘mData’ of undefined at HTMLTableCellElement.eval

0reactions
LoopSuncommented, Nov 22, 2017

Hi, I found the code in datatable [official page] (url:https://datatables.net/reference/api/destroy())

var table = $('#myTable').DataTable();
 
$('#submit').on( 'click', function () {
    $.getJSON( 'newTable', null, function ( json ) {
        table.destroy();
        $('#myTable').empty(); // empty in case the columns change
 
        table = $('#myTable').DataTable( {
            columns: json.columns,
            data:    json.rows
        } );
    } );
} );

Solution !!!

  1. add id or other in the table tag
<table id="example-datatable" datatable [dtOptions]="dtOptions" [dtTrigger]="dtTrigger"   class="table row-border hover" *ngIf="dataOptions">
<table>
  1. add the code in reRender() function
    if (this.datatableElement.dtInstance) {
      this.datatableElement.dtInstance.then((dtInstance: DataTables.Api) => {
        dtInstance.destroy();
        $('#example-datatable').empty();    # Empty the datatable
      });
    }
Read more comments on GitHub >

github_iconTop Results From Across the Web

TypeError: Cannot read property 'mData' of undefined
I have this error: TypeError: Cannot read property 'mData' of undefined. I've read it might be because the table has no thead or...
Read more >
Datatables: Cannot read property 'mData' of undefined
For a table with 7 colums, the following does not work and we see "Cannot read property 'mData' of undefined" in the javascript...
Read more >
Angular 4 + DataTables = Cannot read property 'mData' of ...
Angular 4 + DataTables = Cannot read property 'mData' of undefined at HTMLTableCellElement.eval.
Read more >
Datatables Cannot read property mData of undefined
Privacy: Your email address will only be used for sending these notifications. Add answer. Related Questions In JQuery.
Read more >
Datatable Error Cannot Read Property 'Mdata' Of Undefined
Cannot read property 'mData' of undefined TypeError . 4. . 5. title1 . 6. title2 Uncaught TypeError: Cannot read property 'value' of null...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found