Я реализовал Angular jQuery .Datatables в ngb-tabset (http://l-lin.github.io/angular-datatables/# / advanced / rerender ). Я установил все модули узла и выполнил необходимую настройку, и она отлично работает после первого запуска, но когда я перехожу с одной вкладки на другую и возвращаюсь на вкладку с данными, данные загружаются из API успешно, но данные отказываются для правильной инициализации.
Может ли кто-нибудь мне помочь?
Искал много в Google, чтобы найти решение, но не получил. Буду очень признателен за любую помощь, так как я действительно застрял здесь в течение последней недели.
Пожалуйста, найдите ниже мой код
import { Component, OnInit, OnDestroy, ViewChild, AfterViewInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { TaskService } from "../task.service";
import { Task } from '../tasks';
import { Subject, Subscription} from 'rxjs';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { FormGroup, FormBuilder, FormControl } from '@angular/forms';
import { NgbTabChangeEvent } from '@ng-bootstrap/ng-bootstrap';
import { DataTableDirective } from 'angular-datatables';
@Component({
selector: 'app-approveleave',
templateUrl: './approveleave.component.html',
styleUrls: ['./approveleave.component.css']
})
export class ApproveleaveComponent implements AfterViewInit, OnDestroy, OnInit {
@ViewChild(DataTableDirective, {static: false})
dtElement: DataTableDirective;
title = 'modal2';
submitted = false;
tasks: any =[];
id: number;
dtOptions: DataTables.Settings = {};
dtTrigger: Subject<any> = new Subject();
isDtInitialized:boolean = false
taskclass: Task = new Task();
subscription: Subscription;
constructor(private taskService: TaskService, private router: Router, private route:ActivatedRoute, private fb: FormBuilder, private modalService: NgbModal) {
displayToConsole(dtElement: DataTableDirective): void
{
dtElement.dtInstance.then((dtInstance: DataTables.Api) =>
console.log(dtInstance));
}
ngOnInit() {
this.dtOptions = {
destroy: true,
pagingType: 'full_numbers',
pageLength: 5,
processing: true
};
this.id = JSON.parse(localStorage.getItem('id'));
console.log(this.id);
this.subscription = this.taskService.getApproveTasklist(this.id).subscribe((tasks: Task[])=>{
this.tasks = tasks;
// this.dtTrigger.next();
//this.rerender();
//console.log("Hi...");
// this.dtElement.dtInstance.then((dtInstance: DataTables.Api) => {
// // Destroy the table first
// dtInstance.clear();
// dtInstance.destroy();
// // Call the dtTrigger to rerender again
// this.dtTrigger.next();
// });
if (this.isDtInitialized) {
this.dtElement.dtInstance.then((dtInstance: DataTables.Api) => {
dtInstance.destroy();
this.dtTrigger.next();
console.log("Tesst1");
});
} else {
this.isDtInitialized = false
this.dtTrigger.next();
console.log("Tesst2");
}
}
changeTab(event) {
if (event.nextId == '1') {
console.log('First Tab');
this.rerender();
// this.subscription = this.taskService.getApproveTasklist(this.id).subscribe((tasks: Task[])=>{
// this.tasks = tasks;
// this.dtTrigger.next();
// });
} else if (event.nextId == '2') {
// Action for second tab
console.log('Second Tab');
} else if (event.nextId == '3') {
// Action for second tab
console.log('Third Tab');
}
}
ngAfterViewInit(): void {
this.dtTrigger.next();
}
rerender(): void {
this.dtElement.dtInstance.then((dtInstance: DataTables.Api) => {
// Destroy the table first
// dtInstance.draw();
dtInstance.destroy();
// Call the dtTrigger to rerender again
this.tasks;
this.dtTrigger.next();
});
}
// rerender(): void {
// this.subscription = this.taskService.getApproveTasklist(this.id).subscribe((tasks: Task[])=>{
// this.tasks = tasks;
// this.dtTrigger.next();
// });
// }
ngOnDestroy(): void {
// ngOnDestroy() {
// Do not forget to unsubscribe the event
// this.dataTable.unsubscribe();
if (!!this.subscription) this.subscription.unsubscribe();
//this.subscription.unsubscribe();
this.dtTrigger.unsubscribe();
//this.dtTrigger.next();
console.log('this.dtTrigger.unsubscribe()', this.dtTrigger);
}
}
<!-- Tabs -->
<ngb-tabset
activeId="tab-1"
(tabChange)="changeTab($event)"
#myTabSet="ngbTabset" class="testTab"
>
<ngb-tab title="Test1" [id]="1" id="tab-1">
<ng-template ngbTabContent>
<div class="testContent">
<section class="component-section" id="employee">
<!-- <table class="table pmd-table table-hover pmd-table-card"> -->
<table id="approveTable" class="table table-striped table-bordered table-sm row-border hover" datatable [dtOptions]="dtOptions" [dtTrigger]="dtTrigger">
<thead class="thead-light">
<tr>
<th>Name</th>
<th>Type</th>
<th>Start Date</th>
<th>End Date</th>
<th>Day</th>
<th>Reason</th>
<th>Days</th>
<th class="text-center">Action</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let task of tasks.taskreq">
<td width="12%">
{{task.e_name}}
</td>
<td width="12%">
{{leave.e_type_name}}
</td>
<td width="12%">{{lask.lr_from_date | date: 'dd/MM/yyyy'}}</td>
<td width="12%">{{lask.lr_to_date | date: 'dd/MM/yyyy'}}</td>
<td width="8%">lask.lr_day
</td>
<td width="25%">{{task.lr_reason}}</td>
<td width="5%">{{task.lr_total_days}}</td>
<td width="16%" class="text-center">
<button (click)="approveTask(task.lr_id)" title="Approve" class="btn btn-info" ><i class="far fa-check-square"></i></button>
</td>
</tr>
</tbody>
</table>
</section>
</div>
</ng-template>
</ngb-tab>
<ngb-tab title="Test2" [id]="2" id="tab-2">
<ng-template ngbTabContent>
<div class="testContent">
<p>Test2 content here</p>
</div>
</ng-template>
</ngb-tab>
<ngb-tab title="Test3" [id]="3" id="tab-3">
<ng-template ngbTabContent>
<div class="testContent">
<p>Test3 content here</p>
</div>
</ng-template>
</ngb-tab>
</ngb-tabset>
<!-- Tabs end -->