When attempting to integrate jQuery plugins with Angular 2, there are three distinct scenarios:
1. ONLOAD: Initializing the plugin on page load works smoothly with the following code snippet:
ngAfterViewChecked(){
...
$('#somedatatable1').DataTable()
...
}
2. ONCLICK: Triggering the plugin on click involves fetching server-generated HTML (although it's recommended to transfer only data in JSON format) and feeding it into the page before initializing the DataTable plugin:
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">
HTML output after parsing retrieved data:
<div id="contents">
<div id="somedatatable2">
....
</div>
</div>
The question here is: Where should "$('.somedatatable2').datatables();" be placed for proper functionality? The aim is to retrieve and parse everything fully before calling the jQuery plugin for it to work correctly.
3. ONCLICK SUBCOMPONENT: Activating a subcomponent upon clicking:
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 retrieval and parsing:
<div id="subcomponentbody">
<div id="somedatatable3">
....
</div>
</div>
subcomponent.ts
ngAfterViewChecked(){
...
$('#somedatatable3').DataTable()
...
}
The question arises: Is initiating the plugin in the subcomponent via ngAfterViewChecked the preferred choice?
An additional question: What is the correct way to include a jQuery plugin? Importing the plugin using "import * as Datatables from 'jquery-datatables'" and then running "npm install jquery-datatables --save" followed by adding the plugin's CSS file into @Component styleUrls like ['datatables.css','main.css']. Does this method align with best practices?