Skip to content

Commit

Permalink
fix bug: async require oldMatcher
Browse files Browse the repository at this point in the history
The select2('data') method was called on an element that is not using
Select2
  • Loading branch information
gaop committed Jan 31, 2018
1 parent ec9ad54 commit 4f84bfb
Showing 1 changed file with 20 additions and 13 deletions.
33 changes: 20 additions & 13 deletions lib/ng2-select2.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,15 +59,15 @@ export class Select2Component implements AfterViewInit, OnChanges, OnDestroy, On
}
}

ngOnChanges(changes: SimpleChanges) {
async ngOnChanges(changes: SimpleChanges) {
if(!this.element) {
return;
}

if(changes['data'] && JSON.stringify(changes['data'].previousValue) !== JSON.stringify(changes['data'].currentValue)) {
this.initPlugin();
await this.initPlugin();

const newValue: string = this.element.val();
const newValue: string = this.element.val() as string;
this.valueChanged.emit({
value: newValue,
data: this.element.select2('data')
Expand All @@ -90,9 +90,9 @@ export class Select2Component implements AfterViewInit, OnChanges, OnDestroy, On
}
}

ngAfterViewInit() {
async ngAfterViewInit() {
this.element = jQuery(this.selector.nativeElement);
this.initPlugin();
await this.initPlugin();

if (typeof this.value !== 'undefined') {
this.setElementValue(this.value);
Expand All @@ -110,7 +110,7 @@ export class Select2Component implements AfterViewInit, OnChanges, OnDestroy, On
this.element.off("select2:select");
}

private initPlugin() {
private async initPlugin() {
if(!this.element.select2) {
if(!this.check) {
this.check = true;
Expand All @@ -134,14 +134,13 @@ export class Select2Component implements AfterViewInit, OnChanges, OnDestroy, On
Object.assign(options, this.options);

if(options.matcher) {
jQuery.fn.select2.amd.require(['select2/compat/matcher'], (oldMatcher: any) => {
options.matcher = oldMatcher(options.matcher);
this.element.select2(options);
let oldMatcher: any = await this.requireOldMatcher();
options.matcher = oldMatcher(options.matcher);
this.element.select2(options);

if (typeof this.value !== 'undefined') {
this.setElementValue(this.value);
}
});
if (typeof this.value !== 'undefined') {
this.setElementValue(this.value);
}
} else {
this.element.select2(options);
}
Expand All @@ -151,6 +150,14 @@ export class Select2Component implements AfterViewInit, OnChanges, OnDestroy, On
}
}

private async requireOldMatcher() : Promise<any> {
return new Promise<any[]>(resolve => {
jQuery.fn.select2.amd.require(['select2/compat/matcher'], (oldMatcher: any) => {
resolve(oldMatcher);
});
});
}

private setElementValue (newValue: string | string[]) {
if(Array.isArray(newValue)) {
for (let option of this.selector.nativeElement.options) {
Expand Down

0 comments on commit 4f84bfb

Please sign in to comment.