1

我正在使用smartadmin角度模板。在一种形式中,我使用select2的是已经作为指令存在于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'])
    })
  }

}

我在我的组件模板中使用它,并select2在从服务器获取数据后将数据添加到选项中。

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

现在如何获取我从中选择的选项的值select2。我尝试在组件的模板中使用[(ngModel)](click)绑定,但这对我不起作用。

4

2 回答 2

1

为此,您必须使用ngAfterViewInit生命周期方法,因为select2insmartadmin是他们定义的指令。对于事件绑定和其他方法,您必须在ngAfterViewInit. 代码应该像

ngAfterViewInit(){
   $('.select2').on('select2:select', (event) => {
       // Code you want to execute when you hit enter in select2 input box   
   });
}
于 2018-10-17T06:08:22.480 回答
0

你也可以JQuery通过添加一个Id选择标签来做到这一点

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

在你的ngAfterViewInit()

ngAfterViewInit(){
   $('#symbolId').on('change', (event) => {
       var symbolSelected= event.target.value;
       //you can use the selected value
   });
}
于 2018-10-17T06:23:05.580 回答