更新
虽然我们能够选中/取消选中,但是为每个mat-select实现订阅真的很烦人。
所以这是解决方案,我创建了一个Directive,它有一个事件checkboxChanged,当mat-option 被选中/取消选中时调用它
在您的项目中实现此功能
1.只需将文件mat-select-checkbox-changes.directive.ts从here复制并粘贴到您的项目中并相应地导入并开始使用如下。
<mat-select multiple appMatSelectCheckboxChanges [(ngModel)]="selectedFood" [compareWith]="compareWith" (checkboxChanged)="checkboxChanged($event)">
<mat-option *ngFor="let food of foods" [value]="food.value">{{food.viewValue}}</mat-option>
</mat-select>
checkboxChanged(evt: { value: Food, isChecked: boolean }) {
console.log(`${evt.value} is ${evt.isChecked ? 'checked' : 'unchecked'}`);
}
在下面添加指令代码(以防链接损坏)
import { Directive, EventEmitter, Output, OnDestroy } from "@angular/core";
import { MatSelect } from "@angular/material/select";
import { Subscription } from "rxjs";
interface IMatSelectCheckboxChanges {
value: any;
isChecked: boolean;
}
@Directive({
selector: "[appMatSelectCheckboxChanges]"
})
export class MatSelectCheckboxChangesDirective implements OnDestroy {
@Output() checkboxChanged = new EventEmitter<IMatSelectCheckboxChanges>();
subscription: Subscription;
constructor(private matSelect: MatSelect) {
this.subscription = this.matSelect.optionSelectionChanges.subscribe(matOption => {
if (matOption.isUserInput) {
this.checkboxChanged.next({ value: matOption.source.value, isChecked: matOption.source.selected });
}
}
);
}
ngOnDestroy() {
if (this.subscription) {
this.subscription.unsubscribe();
}
}
}
原创
使用optionSelectionChanges observable。
1.获取mat-select参考
//if there is only one mat-select
@ViewChild(MatSelect) matSelect: MatSelect;
//if there are multiple, then add unique local template variables
@ViewChild('#favFood') favFoodselect: MatSelect;
@ViewChild('#favAnimal') favAnimalselect: MatSelect;
2.订阅更改
this.subscription = this.matSelect.optionSelectionChanges.subscribe(matOption => {
if (matOption.isUserInput) {
console.log(`${matOption.source.viewValue} is ${matOption.source.selected ? 'checked' : 'unchecked'}`);
}
});
一些细节
如果您最初分配任何值(默认值),也会调用上述订阅
为了防止这种情况,请使用matOption.isUserInput添加if检查
别忘了取消订阅可观察
ngOnDestroy() {
if (this.subscription) {
this.subscription.unsubscribe();
}
}
Stackblitz Demo