I'm writing an angular 4.1.2 component as a wrapper for select2 4.0.3
I'm quite new with angular and typescript so maybe there is something that I've missed...
I know that there are some available npm package that I could use in order to obtain that but I'd like to keep my staff as simple as possible
actually at the moment the component I wrote is working,
but there is a piece of code that I can't understand why must be like that and I'd like you to give me some points.
conside this pseudo-typescript-code (actually i have a lot of stuff inside base and abstract classes so to make it more readable I cut-n-pasted in a single component....
NOTE : I declared both jquery and select 2 as any because I included their scripts inside the page (not with npm / 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 {
// CUT ...
ngAfterViewInit() {
// validations
// CUT ...
var $select = $(this.select.nativeElement);
// basic configuration
$select.select2({
// CUT ...
ajax: {
url: this.dataUrl,
dataType: 'json',
// CUT ...
},
});
// on select 2 change => trigger model change
$select.on("change", (event: any) => {
// CUT ...
});
// 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);
*/
}
}
what I can't understand is why do I have to use "windows.setTimeout" to trigger the selection ...
if I write directly the select2 trigger the select2 component is not updated at all...
NOTE : I tried to implement the class inside AfterContentInit and leave only the trigger of the selection inside the AfterViewInit (so it should be called after the configuration...) but it doesn't work.
do you have any hint to give me?
UPDATE : I tried using document ready... and I get ExpressionChangedAfterItHasBeenCheckedError
$(() => {
console.log("ready");
$(this.select.nativeElement).select2("trigger", "select", { data: { id: "123123", text: "item 123123" } });
});
then I founded this : ExpressionChangedAfterItHasBeenCheckedError Explained maybe
now I'm reading about this issue...