这是这个奇怪的部分的代码:
ngOnInit(): void
{
$(document).ready(function() {
(<any>$("#the_table")).DataTable();
(<any>$('#selectpicker')).selectpicker();
}
if ($.isEmptyObject(this.route.snapshot.params) === false)
{
this.id = +(<any>this.route.snapshot.params).id;
}
let pass = {type: "reports"};
this.searchService.searchHttp( {type: "reports"} ).then( (response: any) =>
{
this.reports = response;
console.log(response);
});
}
这是“搜索”的代码,没有被破坏。
ngOnInit(): void
{
$(document).ready(function() {
(<any>$('.selectpicker')).selectpicker();
});
this.tags = this.searchService.get_tags();
this.draw_table();
}
draw_table()
{
let json = JSON.stringify(this.tags);
this.table = (<any>$("#ajax_table")).DataTable({
"dom": 'Bfrtip',
"processing": true,
"ajax": {
"url": "app/php/search.php" + "?json=" + encodeURIComponent(json) + "&type=search",
},
"columns": [
{ "data": "id" },
{ "data": "ref" },
{ "data": "date" },
{ "data": "title" },
{ "data": "site" },
{ "data": "location" }
],
"filter": true,
"select": true,
"autoWidth": false,
"buttons": [
{
"text": "test",
action: () =>
{
console.log(table.rows( { selected: true } ).data());
let data = table.rows( { selected: true } ).data()[0];
data = (data) ? data : null;
this.router.navigate(['/main', data ]);
},
enabled: false
}
],
//"destroy": true
});
let table = this.table;
table.on( 'select', function () {
table.button(0).enable(true);
} );
table.on( 'deselect', function () {
table.button(0).enable(false);
});
}
如果有人有任何想法,请随时指出。
更新的 试过NgZone:
ngOnInit(): void
{
if ($.isEmptyObject(this.route.snapshot.params) === false)
{
this.id = +(<any>this.route.snapshot.params).id;
}
let pass = {type: "reports"};
this.searchService.searchHttp( {type: "reports"} ).then( (response: any) =>
{
this.reports = response;
console.log(response);
this.ngZone.onStable.first().subscribe( () => {
(<any>$('#selectpicker')).selectpicker();
(<any>$("#the_table")).DataTable();
});
});
}
答案 0 :(得分:1)
您需要照顾的几点。
首先在angular2中使用document.ready是侮辱angular2。删除它。
其次要知道如何在angular2中使用jQuery插件,你需要首先从http服务获取数据并将其分配给成员变量以将其绑定在页面上。然后你应该订阅onStable事件,确保所有数据绑定都已完成并且数据已在页面上呈现。
onStable事件只会被触发一次。
constructor(private ngZone: NgZone) {}
ngOnInit() {
this.searchService.searchHttp( {type: "reports"} ).then( (response: any) =>
{
this.reports = response;
// waiting until select options are rendered
this.ngZone.onStable.first().subscribe(() => {
$('#selectpicker')).selectpicker();
});
});
}
}
onStable:EventEmitter: 通知最后一次onMicrotaskEmpty何时运行并且没有更多的微任务,这意味着我们即将放弃VM转向。此事件只被调用一次。
答案 1 :(得分:0)
使用public ngAfterViewChecked(): void {}
解决此问题。