[英]Angular 2 DataTable
我正在嘗試在angular 2應用程序上使用Jquery 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腳本。
這是屏幕截圖: http : //hpics.li/efa3c31
請注意,您正在使用ngOnInit()
生命周期掛鈎中的jQuery訪問DOM。
ngOnInit()
在Angular首先顯示數據綁定屬性並設置指令/組件的輸入屬性后,初始化指令/組件。 在第一個ngOnChanges()之后調用一次。 -https://angular.io/guide/lifecycle-hooks
但是在您的情況下,必須先呈現組件的視圖,然后才能訪問DOM。
ngAfterViewInit()
在Angular初始化組件的視圖和子視圖之后響應。 在第一個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();
}
}
希望這能解決您的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.