1

Eu estou utilizando essa datatable: Angular Datatables

Segui a risca os exemplos citados no site, mas a datatable não aparece (não carrega), apenas a table do html aparece na tela.

Alguém sabe como resolver isso? Pois parece tão simples nos exemplos do site que não pensei que ia passar por tanta dificuldade.

Código abaixo: PS: quando tiro o comando "[dtOptions]="dtOptions" [dtTrigger]="dtTrigger"" da tabela, ai exibe o componente.

<h4 class="m-3"> Modulos</h4>
<nav class="nav">
    <button class="btn btn-success m-3" [routerLink]="['new']">Criar Módulo</button>
</nav>
<table datatable [dtOptions]="dtOptions" [dtTrigger]="dtTrigger" class="table table-light mx-3 text-secondary">
  <thead class="thead-light">
    <tr>
      <th>ID</th>
      <th>Nome</th>
      <th>Descrição</th>
      <th>Sistema</th>
      <th>Setor</th>
      <th>Modulo Pai</th>
      <th>Ações</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let m of modulos">
      <th>{{ m.id_modulo }}</th>
      <th>{{ m.nome_modulo }}</th>
      <th>{{ m.descricao }}</th>
      <th>{{ m.nome_sistema }}</th>
      <th>{{ m.nome_setor }}</th>
      <th>{{ m.nome_modulo_pai }}</th>
      <th><button class="btn btn-sm btn-info mr-2" [routerLink]="[m.id_modulo, 'edit']">Editar</button>
        <button class="btn btn-sm btn-danger" (click)="onDelete(m.id_modulo)">Deletar</button>
      </th>
    </tr>
  </tbody>
</table>

<ng-template #deleteModal>
  <div class="modal-body text-center">
    <p>Tem certeza que quer deletar?</p>
    <button type="button" class="btn btn-default" (click)="onConfirmDelete()">Sim</button>
    <button type="button" class="btn btn-primary" (click)="onDeclineDelete()">Não</button>
  </div>
</ng-template>
import { Component, OnInit, ViewChild, OnDestroy } from '@angular/core';
import { BsModalService, BsModalRef } from 'ngx-bootstrap/modal';
import { Router } from "@angular/router";
import { Subject } from 'rxjs';

import { Modulos } from '../../interface/modulos';
import { ModulosService } from '../../services/modulos.service';

@Component({
  selector: 'app-modulo',
  templateUrl: './modulos.component.html',
  styleUrls: ['./modulos.component.css']
})
export class ModulosComponent implements OnDestroy, OnInit {

  public modulos: Modulos[];
  deleteModalRef: BsModalRef;
  deleteId: number;
  dtOptions: DataTables.Settings = {};
  dtTrigger: Subject<any> = new Subject();

  @ViewChild('deleteModal') deleteModal;

  constructor(private modulosService: ModulosService,
              private bsModalService: BsModalService,
              private router: Router) { }

  ngOnInit() {
    this.dtOptions = {
      pagingType: 'full_numbers',
      pageLength: 2
    };

    this.getList();
  }

  getList() {
    this.modulosService.getList().subscribe(
      (modulos: Modulos[]) => {this.modulos = modulos; this.dtTrigger.next();},
      (error) => {console.log(error); }
    );
  }
  ngOnDestroy(): void {
    // Do not forget to unsubscribe the event
    this.dtTrigger.unsubscribe();

  }
  onDelete(id: number) {
    this.deleteId = id;
    this.deleteModalRef = this.bsModalService.show(this.deleteModal, {class: 'modal-sm'});
  }
  onConfirmDelete() {
    this.delete(this.deleteId);
    this.deleteModalRef.hide();
  }
  onDeclineDelete() {
    this.deleteModalRef.hide();
  }
  private delete(id: number) {
    this.modulosService.delete(id).subscribe(
      (response) => {console.log(response); this.getList(); },
      (error) => {console.log(error); }
    );
  }
}

Erro que aparece: inserir a descrição da imagem aqui

No app.module está importado o Datatables

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { ModalModule, BsModalRef } from 'ngx-bootstrap/modal';
import { BsDropdownModule } from 'ngx-bootstrap';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { CommonModule } from '@angular/common';
import { DataTablesModule } from 'angular-datatables';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { MainComponent } from './main/main.component';

@NgModule({
   declarations: [
      AppComponent,
      MainComponent
   ],
   imports: [
      AppRoutingModule,
      BrowserModule,
      BsDropdownModule.forRoot(),
      CommonModule,
      DataTablesModule,
      FormsModule,
      HttpClientModule,
      ModalModule.forRoot(),
      NgbModule
   ],
   providers: [
      BsModalRef
   ],
   bootstrap: [
      AppComponent
   ]
})
export class AppModule { }

Versão do Datatables: 6.9.0 Versão do Jquery: 6.9.0

4
  • 1
    O console exibe alguma mensagem de erro? 5/05/2019 às 1:34
  • 1
    Já posso adiantar que um possível erro é o fato de no <tbody> ter tags <td> vazias 5/05/2019 às 17:08
  • @MauricioHartmann, fiz essa alteração e não funcionou. postar o erro e algumas alterações que fiz. 6/05/2019 às 12:19
  • Editei a pergunta e acrescentei o erro e as alterações no código 6/05/2019 às 12:30

2 Respostas 2

1

Vi o código e me parece que o ModulosComponent não é um componente do AppModule, ou seja, o seu componente está vinculado à outro módulo. Realize o import do DataTablesModule no módulo ModulosModule e efetue o teste novamente.

O Angular tem um encapsulamento muito específico, os componentes importados por aquele módulo só podem utilizar os imports daquele módulo.

O certo seria trabalhar com uma Shared, que realiza o import desses módulos reutilizados em outros pontos da aplicação, segue referência da documentação do Angular sobre o assunto: Compartilhando Módulos

1
  • Realmente, foi só colocar o import do datatables no modulo do "Modulos" e tudo funcionou normalmente. Muito Obrigado pela explicação e ajuda!!! 8/05/2019 às 16:44
0

Você possui um erro de importação envolvendo dtOptions.

Can't bind to 'dtOptions' since it isn't a know property of 'table'.

Não é possível aplicar 'dtOptions' pois não é uma propriedade conhecida de 'table'.

Verifique se o módulo correspondente está sendo importado corretamente em @NgModule.

1
  • Sim está, adicionei o app.module na pergunta para você dar uma olhada. 6/05/2019 às 12:34

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .