- 确认已经正确引入了Bootstrap Multiselect库和相应的CSS样式:
- 在Angular组件中引入并初始化Bootstrap Multiselect:
import {Component, ElementRef, OnInit, ViewChild} from "@angular/core";
declare var $: any; // 引入jQuery
@Component({
selector: 'app-multiselect',
templateUrl: './multiselect.component.html'
})
export class MultiselectComponent implements OnInit {
@ViewChild('multiselect') elem: ElementRef;
ngOnInit() {
let options = {
includeSelectAllOption: true,
enableFiltering: true,
maxHeight: 120
};
$(this.elem.nativeElement).multiselect(options);
}
}
- 在HTML模板中添加multiselect的HTML元素和必要的配置选项:
- 在组件销毁的时候,需要手动销毁multiselect这个实例,否则会出现内存泄漏的问题:
import {Component, ElementRef, OnDestroy, ViewChild} from "@angular/core";
declare var $: any; // 引入jQuery
@Component({
selector: 'app-multiselect',
templateUrl: './multiselect.component.html'
})
export class MultiselectComponent implements OnInit, OnDestroy {
@ViewChild('multiselect') elem: ElementRef;
ngOnInit() {
let options = {
includeSelectAllOption: true,
enableFiltering: true,
maxHeight: 120
};
$(this.elem.nativeElement).multiselect(options);
}
ngOnDestroy() {
$(this.elem.nativeElement).multiselect('destroy');
}
}