Skip to content

Instantly share code, notes, and snippets.

@firatkucuk
Created April 8, 2017 07:44
Show Gist options
  • Save firatkucuk/07fcccde8cb7c0600e601406b53b0340 to your computer and use it in GitHub Desktop.
Save firatkucuk/07fcccde8cb7c0600e601406b53b0340 to your computer and use it in GitHub Desktop.
import {AbstractControl} from '@angular/forms';
import {DbService} from '../service/db.service';
import {isArray} from 'util';
declare const $: any;
export class TagInput {
private _inputItem: any;
constructor(selector: string, control: AbstractControl, collection: string, db: DbService) {
this._inputItem = $(selector);
this._inputItem.select2({
ajax : {
transport: (params, success) => {
db.getSuggestList(collection, params.data.term, []).then((data) => {
if (!data) {
success({results: []});
} else {
success({results: data});
}
});
},
dataType : 'json',
},
escapeMarkup : function (markup) {
return markup;
}, // let our custom formatter work
minimumInputLength: 1,
templateResult : (result) => `<strong>${result.name}</strong>`,
templateSelection : (result) => result.name
})
.on('select2:select', function (e) {
if (!control.value || (isArray(control.value) && control.value.length === 0)) {
control.setValue([e.params.data]);
} else {
control.value.push(e.params.data);
}
})
.on('select2:unselect', function (e) {
if (control.value || (isArray(control.value) && control.value.length > 0)) {
for (const i in control.value) {
if (control.value[i].id === e.params.data.id) {
control.value[i].splice(i, 1);
break;
}
}
}
});
}
setValue(value: any): void {
this._inputItem.select2('val', {id: '1', text: 'vadaa', element: new Option('vadaa', '1')});
this._inputItem.val({id: '1', text: 'vadaa', element: new Option('vadaa', '1')});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment