我使用的是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)绑定,但这对我来说行不通。
发布于 2018-10-17 06:08:22
为此,您必须使用ngAfterViewInit生命周期方法,因为select2 in smartadmin是他们定义的指令。对于事件绑定和其他方法,您必须在ngAfterViewInit中声明它。代码应该是
ngAfterViewInit(){
$('.select2').on('select2:select', (event) => {
// Code you want to execute when you hit enter in select2 input box
});
}发布于 2018-10-17 06:23:05
您也可以通过添加一个选择标记的JQuery来实现这一点。
<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
});
}https://stackoverflow.com/questions/52642894
复制相似问题