Integrate Select2 into the Angular2 app

后端 未结 2 1064
走了就别回头了
走了就别回头了 2020-12-28 21:03

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

相关标签:
2条回答
  • 2020-12-28 21:14

    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: `<select #select class="form-control"></select>`
    })
    
    export class CustomSelectComponent implements AfterViewInit {
        @ViewChild('select') private select: ElementRef;
        @Input() items: any[];
        @Input() options: any = {};
        @Input() value: any;
        @Output() valueChange = new EventEmitter<string[]>();
    
        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

    <custom-select [items]="array" [options]="{multiple:true}" (valueChange)="update($event)" [value]="valueVar"></custom-select>
    
    0 讨论(0)
  • 2020-12-28 21:25

    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 :)

    0 讨论(0)
提交回复
热议问题