【问题标题】:retrieving selected option from select2 in smartadmin从 smartadmin 中的 select2 检索选定的选项
【发布时间】:2018-10-04 09:01:47
【问题描述】:

我正在使用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) 绑定,但这对我不起作用。

【问题讨论】:

    标签: angular jquery-select2 smartadmin


    【解决方案1】:

    为此,您必须使用ngAfterViewInit 生命周期方法,因为smartadmin 中的select2 是他们定义的指令。对于事件绑定和其他方法,您必须在ngAfterViewInit 中声明它。代码应该是这样的

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

    【讨论】:

      【解决方案2】:

      您也可以使用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
         });
      }
      

      【讨论】:

        猜你喜欢
        • 2014-07-17
        • 2016-03-30
        • 2018-04-03
        • 1970-01-01
        • 2015-12-13
        • 1970-01-01
        • 1970-01-01
        • 2017-01-07
        • 1970-01-01
        相关资源
        最近更新 更多