I\'m trying to integrate Select2 into the Angular2 app I\'m building. I managed to get select2 running and my multiple selects are tr
I've made my own implementation of it, with options, value, and available items as Input params of my component. This is my first version of it, it could be very flexible and augmented pretty easily.
import { Component, ElementRef, Input, Output, AfterViewInit, EventEmitter, ViewChild } from '@angular/core';
declare var $: any;
@Component({
selector: 'custom-select',
template: ``
})
export class CustomSelectComponent implements AfterViewInit {
@ViewChild('select') private select: ElementRef;
@Input() items: any[];
@Input() options: any = {};
@Input() value: any;
@Output() valueChange = new EventEmitter();
constructor() { }
ngAfterViewInit() {
let selectElement = $(this.select.nativeElement);
if (this.isMultiple()) {
selectElement.attr('multiple', true);
}
selectElement.select2({
data: $.map(this.items, (obj: any) => {
let item = {
id: this.options.identifier ? obj[this.options.identifier] : obj.id,
text: this.options.name ? obj[this.options.name] : obj.name
};
if ($.trim(item.id) === '') { console.warn(`No 'id' value has been set for :`, obj); }
if ($.trim(item.text) === '') { console.warn(`No 'name' value has been set for :`, obj); }
return item;
})
});
$(selectElement).val(this.value).trigger('change');
selectElement.on('change', (e: any) => {
this.valueChange.emit($(e.target).val());
});
};
private isMultiple() {
return !!(this.options && this.options.multiple === true);
}
}
And you can call it like that