假设我们在template中添加了一个ng2-select
[html]<ng-select [allowClear]="true" [items]="selectGroup" (selected)="updateGroupSelected($event)" placeholder="请选择"></ng-select>
[/html]
对里面的参数作下简单说明
allowClear:选择完select后,开启点击X,清除select内容
item:一个数组,也就是类似于select中的option,由id跟text这2个键值组成,如下
[js]selectGroup = [{id:"1",text:"第一个option"},{id:"2",text:"第二个option"}]
[/js]
selected:选完选项后触发的事件,如下
[js]public updateGroupSelected(value: any): void {
console.log(value)
}
[/js]
假如要在某个点击事件后,显示已经选中的select,(我这边的场景是选中某个用户,出现一个弹窗,弹窗中有select,默认显示该用户当前的组别)
template作如下修改(也就是增加一个ID 为defaultGroup)
[html]<ng-select #defaultGroup [allowClear]="true" [items]="selectGroup" (selected)="updateGroupSelected($event)" placeholder="请选择"></ng-select>
[/html]
component中
[js]import { SelectComponent } from ‘ng2-select’;
…
@ViewChild(‘defaultGroup’) public ngSelectGroup: SelectComponent;
…..
updateGroupSelected(){
this.ngSelectGroup.active = [];//这里定义默认选中的为一个空数组,此处可以另作处理,设置想要默认选中的option
//例:this.ngSelectGroup.active= [{id:"1",text:"默认的option"}]
…..
}
[/js]