2017-06-21 65 views
0

我想在角2應用上使用Jquery DataTable,我已經成功安裝了它,但仍然無法工作,我不知道爲什麼!Angular 2 DataTable

這裏是我的component.ts文件代碼:

import {Component, ElementRef, OnInit} from '@angular/core'; 
import {Injectable } from '@angular/core'; 
import {Http, Response} from '@angular/http'; 
const $ = require('jquery'); 
const dt = require ('datatables.net'); 
@Component({ 
    selector: 'app-cartographie', 
    templateUrl: './cartographie.component.html', 
    styleUrls: ['./cartographie.component.css', '../../../../node_modules/datatables.net-dt/css/jquery.dataTables.css'] 
}) 

export class CartographieComponent implements OnInit { 
    public data; 
    rootNode: any; 

    constructor(rootNode: ElementRef, private http: Http) { 
    this.rootNode = rootNode; 
    } 
    ngOnInit() { 
    this.getData(); 
    const el = $(this.rootNode.nativeElement).find('#example')[0]; 
    $('#example').DataTable(); 
    } 

    private getData() { 
    this.http.get('http://localhost/ang.php/') 
     .subscribe(res => this.data = res.json()); 
    } 
} 

這裏是component.html文件代碼:

<div class="container"> 
    <div class="panel"> 
    <div class="panel-heading"> 
     <div class="panel-title text-center"> 
     <h3>Cartographie</h3> 
     </div> 
    </div> 
    <div class="panel-body"> 
    </div> 
    <div class="row"> 
     <div class="col lg-12"> 
     <div class="example "> 
      <table class="table table-striped display" id="example" > 
      <thead > 
      <tr> 
       <th>Nom du poste</th> 
       <th>Emploie</th> 
       <th>Metier</th> 
       <th>Famile</th> 
      </tr> 
      </thead> 
      <tbody *ngFor="let grid of data"> 
      <tr class="gradeA"> 
       <td>{{ grid.NomDuPoste}}</td> 
       <td>{{ grid.Emploie}}</td> 
       <td>{{ grid.Metier }}</td> 
       <td>{{grid.Famille}}</td> 
      </tr> 
      </tbody> 
      </table> 
     </div> 
     </div> 
    </div> 
    </div> 
</div> 

搜索和數據的顯示數量不能正常工作。 PS:我的數據來自PHP腳本。

這裏是截圖:在這裏,你正在訪問的ngOnInit()生命週期掛鉤使用jQuery的DOM http://hpics.li/efa3c31

回答

1

通知。

ngOnInit()

初始化角首先顯示後的指令/組件 數據綁定屬性,並設置指令/組件的輸入 屬性。在第一個ngOnChanges()之後調用一次。 - https://angular.io/guide/lifecycle-hooks

但在你的情況下,組件的視圖必須先呈現,然後才能訪問DOM。

ngAfterViewInit()角後

迴應初始化該組件的意見和兒童 意見。在第一個ngAfterContentChecked()之後調用一次。 - https://angular.io/guide/lifecycle-hooks

您應該修改CartographieComponent的這樣的代碼:

import {AfterViewInit} from '@angular/core'; 

// other imports here 

export class CartographieComponent implements OnInit, AfterViewInit { 

    // other code here 

    ngOnInit() { 
    this.getData(); 
    } 

    ngAfterViewInit(){ 
    const el = $(this.rootNode.nativeElement).find('#example')[0]; 
    $('#example').DataTable(); 
    } 

} 

希望這能解決你的問題。

+0

嗨阿布拉爾,感謝您的回答,我試過你的解決方案,但沒有改變,仍然無法正常工作! – sahnoun