retrieving selected option from select2 in smartadmin

461 Views Asked by At

I am using smartadmin angular template. In one form , I am using select2 which is already present as a directive in smartadmin.

import {Directive, ElementRef, OnInit} from '@angular/core';
import {addClassName, removeClassName} from '../../../utils/dom-helpers';

declare var $: any;

@Directive({
  selector: '[select2]'
})
export class Select2Directive implements OnInit {

  constructor(private el: ElementRef) {
    addClassName(this.el.nativeElement, ['sa-cloak', 'sa-hidden'])
  }

  ngOnInit() {
    System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
      $(this.el.nativeElement).select2()
      removeClassName(this.el.nativeElement, ['sa-hidden'])
    })
  }

}

I am using this in my component template and adding data into the select2 options after getting data from the server.

<select select2 style="width:100%;" class="select2" [(ngModel)]="selectedContractDetails.name">
    <option *ngFor="let symbol of service.symbols" value="{{symbol}}">{{symbol}}</option>
</select>

Now how to get the value of the option that I select from select2 . I tried using [(ngModel)] and (click) binding in component's template but this didn't work for me.

2

There are 2 best solutions below

0
On

for this, you have to use ngAfterViewInit life cycle method because select2 in smartadmin is a directive they have defined. For the event bindings and other methods, you have to declare it inside ngAfterViewInit. The code should be like

ngAfterViewInit(){
   $('.select2').on('select2:select', (event) => {
       // Code you want to execute when you hit enter in select2 input box   
   });
}
0
On

you can do this also with JQuery by Just adding an Id to select tag

 <select select2 style="width:100%;" class="select2" id="symbolId" [(ngModel)]="selectedContractDetails.name">
        <option *ngFor="let symbol of service.symbols" value="{{symbol}}">{{symbol}}</option>
    </select>

In your ngAfterViewInit()

ngAfterViewInit(){
   $('#symbolId').on('change', (event) => {
       var symbolSelected= event.target.value;
       //you can use the selected value
   });
}