Radoslav Stoyanov Radoslav Stoyanov - 4 months ago 67
jQuery Question

Angular2 and Select2


I'm trying to integrate

Select2
into the
Angular2
app I'm building. I managed to get
select2
running and my multiple selects are transformed as expected. My problem now is how am I supposed to get the selected values and which event should I use for the binding. I tried binding
(change)
event on the select element but nothing happened. May be I should use some other event on the created by the plugin
select2-container
element?
The
select2
plugin is integrated following this answer.

Anybody tried similar mix? Is it possible to get it work or I have to switch to ng2-select directive instead?

Update

Bonus question :) - Even if I give up
select2
and use standard multiple select, how should I get its value? I tried binding it to a property with
[(ngModel)]="_selectedValues"
but it remains empty when I select any option. Is the multiple checkbox the only way for multiple choice?

Update 2

For the bonus question - the workaround I found was to use one way event binding like
(change)="selectedValues=$event.target.selectedOptions"
. Then I added a
setter
for the
selectedValues
property like this:

public set selectedValues(value: Array<any>) {
this._selectedValues.length = 0;
for(let v of value){
this._selectedValues.push(v.value);
}
};

Answer

The only working solution for the select2 I found, is getting the value with jQuery in the ngAfterViewInit method like this:

jQuery('.fields-select').on(
        'change',
        (e) => this._selectedValues = jQuery(e.target).val()
);

So my final code looks like this:

import {Component, AfterViewInit} from 'angular2/core';

@Component({
    selector: 'filters',
    templateUrl: 'template.html'
})
export class FiltersComponent implements AfterViewInit {

    private _availableFields: Array<any> = ['Value1', 'Value2', 'Value3','Value4'];
    private _selectedFields: Array<string> = [];

    ngAfterViewInit(){
        jQuery('.fields-select').select2();
        jQuery('.fields-select').on(
            'change',
            (e) => this._selectedFields = jQuery(e.target).val()
        );
    };
}

And in the template:

<select id="fields" class="form-control fields-select" multiple="multiple">
    <option *ngFor="#field of _availableFields" [value]="field">{{field}}</option>
</select>

Hope this will save someone's life some day :)

Comments