Exploring the integration of an angular 4.1.2 component as a wrapper for select2 4.0.3 has been quite a learning experience for me.
Being relatively new to angular and typescript, there may be some intricate details that have eluded my grasp...
While I am aware of npm packages that could simplify this process, I prefer keeping things straightforward.
Currently, the component I developed is functional, but there exists a snippet of code that perplexes me, prompting me to seek clarification from you.
Reviewing this pseudo-typescript-code (where I consolidated several elements into a single component for better readability)...
I specified both jquery and select2 as any since I directly included their scripts in the page instead of utilizing npm or angular-components.
declare var $: any;
declare var select2: any;
@Component({
moduleId: module.id,
selector: 'select-x',
template: `
<select #select [(ngModel)]="value">
</select>
`,
providers: [{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => SelectX),
multi: true,
}],
})
export class SelectX {
// OMITTED ...
ngAfterViewInit() {
// validations
// OMITTED ...
var $select = $(this.select.nativeElement);
// basic configuration
$select.select2({
// OMITTED ...
ajax: {
url: this.dataUrl,
dataType: 'json',
// OMITTED ...
},
});
// on select 2 change => trigger model change
$select.on("change", (event: any) => {
// OMITTED ...
});
// set default value [WORKING]
window.setTimeout(() => {
var d = { data: { id: this.value, text: this.text } };
$select.select2("trigger", "select", d);
}, 0);
/* set default value [NOT WORKING]
var d = { data: { id: this.value, text: this.text } };
$select.select2("trigger", "select", d);
*/
}
}
My confusion lies in the necessity of using "window.setTimeout" to activate the selection triggering mechanism...
Directly implementing the select2 trigger seems to result in non-updated behavior of the select2 component...
I did attempt placing the class inside AfterContentInit and retaining only the selection triggering within AfterViewInit to ensure it follows after configuration, but to no avail.
Could you offer any insights or suggestions?
UPDATE: I experimented with using document ready and encountered ExpressionChangedAfterItHasBeenCheckedError
$(() => {
console.log("ready");
$(this.select.nativeElement).select2("trigger", "select", { data: { id: "123123", text: "item 123123" } });
});
This led me to discover ExpressionChangedAfterItHasBeenCheckedError Explained which I am currently researching further...