为了使不带复选框的多选下拉列表正常工作,我们需要通过使用ngModel和ngModelChange来实现选择的跟踪和更新。以下是一个示例代码:
HTML模板:
{{fruit.viewValue}}
组件:
import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
fruits = [
{ value: 'apple', viewValue: 'Apple' },
{ value: 'orange', viewValue: 'Orange' },
{ value: 'banana', viewValue: 'Banana' },
{ value: 'grape', viewValue: 'Grape' }
];
fruitSelect = new FormControl('');
ngOnInit() {
this.fruitSelect.valueChanges.subscribe(() => {
const selectedFruits = this.fruits.filter(
fruit => this.getFruitSelection(fruit.value)
);
console.log('Selected fruits:', selectedFruits);
});
}
getFruitSelection(fruitValue: string) {
return this.fruitSelect.value && this.fruitSelect.value.indexOf(fruitValue) > -1;
}
onDropdownOpened() {
// Set the previous value of the select as the initial value when the dropdown is opened
this.fruitSelect['_previousValue'] = this.fruitSelect.value;
}
onDropdownClosed() {
// Revert to the previous value if empty input is submitted
if (!this.fruitSelect.value || this.fruitSelect.value.length === 0) {
this.fruitSelect.setValue(this.fruitSelect['_previousValue']);
}
}
}
在这个示例中,我们使用了mat-select
下一篇:Angular下拉筛选-按钮