angular实现下拉多选框,angular实现下拉多选框并默认选中几个值
在Angular中,你可以使用ng-multiselect-dropdown
库来实现下拉多选框。首先,你需要安装这个库:
npm install ng-multiselect-dropdown
然后,在你的Angular模块中导入MultiselectDropdownModule
:
import { MultiselectDropdownModule } from 'ng-multiselect-dropdown';
@NgModule({
imports: [
MultiselectDropdownModule
], // ...
})
export class AppModule { }
在你的组件中,你可以这样使用它:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<multiselect
[data]="items"
[(ngModel)]="selectedItems"
[settings]="dropdownSettings"
(onSelect)="onItemSelect($event)"
(onDeSelect)="onItemDeSelect($event)"
(onSelectAll)="onSelectAll($event)"
(onDeSelectAll)="onDeSelectAll($event)">
</multiselect>
`
})
export class AppComponent {
items: any[] = [
{ id: 1, name: 'Option 1' },
{ id: 2, name: 'Option 2' },
{ id: 3, name: 'Option 3' },
// ...
];
selectedItems = [this.items[0], this.items[2]]; // 默认选中的项
dropdownSettings = {
singleSelection: false,
idField: 'id',
textField: 'name',
selectAllText: 'Select All',
unSelectAllText: 'UnSelect All',
itemsShowLimit: 3,
allowSearchFilter: true
};
onItemSelect(item: any) {
console.log(item);
}
onItemDeSelect(item: any) {
console.log(item);
}
onSelectAll(items: any) {
console.log(items);
}
onDeSelectAll(items: any) {
console.log(items);
}
}
在这个例子中,items
是下拉框中显示的选项列表,selectedItems
是默认选中的项,dropdownSettings
定义了下拉框的设置。当用户选择或取消选择选项时,会触发onItemSelect
、onItemDeSelect
等事件。
评论已关闭