I have a component in my angular 2 application which has a dropdown list and a datatable. Based on the name selected from the dropdown list, I want to display the details in the datatable.
HTML -
<div>
<select [(ngModel)]="selectName">
<option *ngFor="let name of nameList" value= {{name.firstName}} >
{{name.firstName}}
</option>
</select>
<button id="submitName" (click)="getData()">Go</button>
</div>
<table id="namesTable" [dtTrigger]="dtTrigger" datatable class="row-border hover">
<thead>
<tr>
<th>ID</th>
<th>First name</th>
<th>Last Name</th>
<th>Middle Name</th>
</tr>
</thead>
<tbody *ngIf="retrievedNames">
<tr *ngFor="let name of retrievedNames">
<td>{{name.id}}</td>
<td>{{name.firstName}}</td>
<td>{{name.lastName}}</td>
<td>{{name.middleName}}</td>
</tr>
</tbody>
</table>
Component.ts file -
import { Component, OnInit } from '@angular/core';
import { Http } from '@angular/http';
import { NetworkService } from './../services/network.service';
import { Subject } from 'rxjs/Rx';
import { Router } from '@angular/router';
@Component({
selector: 'app-namedetails',
templateUrl: './namedetails.component.html',
styleUrls: ['./namedetails.component.css']
})
export class NameDetails implements OnInit {
private nameList: any;
private selectedName:string;
private retrievedNames: any;
dtTrigger: Subject<any> = new Subject();
constructor(private _http:Http, private networkservice : NetworkService,private router: Router) {
}
ngOnInit() {
this.fetchFirstNames();
}
fetchFirstNames(){
this.networkservice.getAllFirstNames()
.subscribe(
res => {
console.log(res);
this.nameList = res;
});
}
fetchAllDetails(){
this.networkservice.getAllNames(this.selectedName)
.subscribe(
res => {
console.log(res);
this.retrievedNames = res;
this.dtTrigger.next();
});
}
getData(){
this.fetchAllDetails();
}
}
Whenever I change the value in the dropdown list - I get an alert saying "Datatable warning: table id= namesTable - Cannot reinitialize DataTable. For more information about this error, please see http://datatables.net/tn/3". I understand that reinitializing the datatable again and again is not allow.
So whenever an item is selected/changed in the dropdown, I want to destroy the old instance of the datatable and create/reinitialize a new one.
How do I do this in angular 2 ?
UPDATE - this Link helped me get rid of the error but I ran into another problem which I have posted here
It is because the reference of the
retrievedNames
object might not have been changed. WhengetData()
is called clear the variable and reload it as below,So by this data table will be removed and loaded again.
I was facing the similar issue but I solved it by destroying the datatable in angular using following code
where DataTables is my table's id. You can write that in fetchAllDetails(). Hope it will help the future viewers.