I'm trying to implement angular-datatables by Louis Lin with angular2.
when I try to get instance of Datatable it gives typeError: Cannot read property 'dtInstance' of undefined .
I'm referring steps from the documentation from here
below is my code
import { Component, OnInit,AfterViewInit,ViewChild } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Rx';
import { DataTableDirective } from 'angular-datatables';
import { EmployeeService } from '../services/employee.service';
import { Employee} from "app/services/employee";
@Component({
selector: 'app-employees',
templateUrl: './employees.component.html',
styleUrls: ['./employees.component.css']
})
export class EmployeesComponent implements OnInit {
employees: Employee[];
private datatableElement: DataTableDirective;
dtOptions: DataTables.Settings = {};
constructor(
private employeeservice:EmployeeService,
private route: ActivatedRoute,
private router: Router,
) {
}
ngOnInit(): void {
this.getEmployee();
this.dtOptions = {
paginationType: 'full_numbers',
displayLength: 5
};
}
displayToConsole(datatableElement: DataTableDirective): void
{
datatableElement.dtInstance.then((dtInstance: DataTables.Api) =>
console.log(dtInstance));
}
getEmployee(){
this.employeeservice.getEmployees()
.subscribe(
employees =>{
this.employees = employees;
console.log(this.employees);
(error:Response) => console.log(error)
},
)
}
deleteEmployee(employee){
if (confirm("Are you sure you want to delete Employee ?")) {
console.log(employee.id);
var index = this.employees.indexOf(employee);
this.employees.splice(index, 1);
this.employeeservice.deleteEmployee(employee.id)
.subscribe(
data =>{
this.emp_data = employee;
},
err => {
alert("Could not delete employee.");
// Revert the view back to its original state
this.employees.splice(index, 0, employee);
},
() => this.router.navigate(['/employees'])
);
}
}
}
Looks like you are using datatableElement
before it has data, you could use a promise to make sure it has data.