When trying to integrate jQuery plugins with Angular 2, we have three scenarios:
1.ONLOAD : initiate plugin on page load, which works great with code below:
ngAfterViewChecked(){
...
$('#somedatatable1').DataTable()
...
}
2.ONCLICK : initiate plugin on click, by retrieving server generated html (I know html should not be transferred in json, but just data, but this is what I have) and feeding it to the page, and then initiate DataTable plugin on that data:
maincomponent.ts
clickDatatableParse(){
this.http.get(this.jsonUrl)
.map(res => res.json())
.subscribe(
data => {
this.data = data
},
err => console.log(err),
() => console.log("fetched!")
)
}
maincomponent.html
<div id="contents" [innerHTML]="data?.htmltable">
PARSED Html output after data is retrieved and parsed
<div id="contents">
<div id="somedatatable2">
....
</div>
</div>
Question is where to put "$('.somedatatable2').datatables();" so it will work properly. So, everything needs to be retrieved and parsed fully, and then call jQuery plugin on it, then it will work.
3.ONCLICK SUBCOMPONENT is when I click, the subcomponent is being activated
maincomponent.ts
clickDatatableParse(){
this.http.get(this.jsonUrl)
.map(res => res.json())
.subscribe(
data => {
this.data = data
},
err => console.log(err),
() => console.log("fetched!")
)
}
maincomponent.html
<div id="subcomponent" [htmldata]="data?.htmltable">
subcomponent.html
<div id="subcomponentbody" [innerHTML]="htmldata">
....
</div>
PARSED Html output after data is retrieved and parsed
<div id="subcomponentbody">
<div id="somedatatable3">
....
</div>
</div>
subcomponent.ts
ngAfterViewChecked(){
...
$('#somedatatable3').DataTable()
...
}
Question is if this is something that should work? I assume that initiating plugin in subcomponent via ngAfterViewChecked better choice or not?
Question is how properly to include jQuery plugin. I think that I should import the plugin via "import * as Datatables from 'jquery-datatables'" and "npm install jquery-datatables --save" before that, and then just put in .css file of the plugin into the @component styleUrls: ['datatables.css','main.css']. Is this proper way to do it?