在Angular中实现多选框筛选列表的方法如下:
首先,创建一个可以显示多选框选项的组件,比如CheckboxListComponent
:
checkbox-list.component.ts:
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-checkbox-list',
template: `
{{ option.label }}
`,
})
export class CheckboxListComponent {
@Input() options: any[];
@Output() selectionChange: EventEmitter = new EventEmitter();
toggleOption(option: any) {
option.checked = !option.checked;
this.selectionChange.emit(this.options.filter(o => o.checked));
}
}
然后,在父组件中使用CheckboxListComponent
来显示多选框选项,并根据选项的变化来筛选列表:
parent.component.html:
- {{ item }}
parent.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})
export class ParentComponent {
checkboxOptions = [
{ label: 'Option 1', checked: false },
{ label: 'Option 2', checked: false },
{ label: 'Option 3', checked: false },
];
list = ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5'];
filteredList = this.list;
filterList(selectedOptions: any[]) {
if (selectedOptions.length === 0) {
this.filteredList = this.list;
} else {
this.filteredList = this.list.filter(item => {
return selectedOptions.some(option => item.includes(option.label));
});
}
}
}
在上述示例中,CheckboxListComponent
接收一个options
数组作为输入,并通过selectionChange
事件发出选中的选项。父组件中的filterList
方法根据选中的选项来筛选列表。
通过以上方法,您可以实现一个Angular多选框筛选列表。