使用点击事件试试这个
<mat-form-field>
<mat-select placeholder="Toppings" [formControl]="toppings" multiple>
<mat-option [value]="1" (click)="selectAll(ev)"
#ev
>SelectAll</mat-option>
<mat-option *ngFor="let topping of toppingList" [value]="topping">{{topping}}</mat-option>
</mat-select>
</mat-form-field>
}
打字稿:
selectAll(ev) {
if(ev._selected) {
this.toppings.setValue(['Extra cheese', 'Mushroom', 'Onion', 'Pepperoni', 'Sausage', 'Tomato']);
ev._selected=true;
}
if(ev._selected==false) {
this.toppings.setValue([]);
}
}
我扩展了 Angular Material 的 MatSelect 以包含以下功能:
工作示例可以在 StackBlitz 上找到,完整的存储库可以在 GitHub
上找到以下是“全选”实现的代码片段
<button *ngIf="isGroup && values.length" mat-icon-button (click)="toggleGroup()">
<mat-icon>
{{ isCollapsed ? 'chevron_right' : 'expand_more' }}
</mat-icon>
</button>
<ng-container *ngIf="values.length" [ngSwitch]="isMultiple">
<mat-checkbox *ngSwitchCase="true" disableRipple matRipple class="mat-option" color="primary"
[ngClass]="{ 'mat-selected': isIndeterminate() || isChecked() }" [indeterminate]="isIndeterminate()"
[checked]="isChecked()" (click)="$event.stopPropagation()" (change)="toggleSelection($event)">
{{text}}
</mat-checkbox>
<span *ngSwitchDefault>
{{text}}
</span>
</ng-container>
import { Component, Input, ViewEncapsulation, OnChanges, SimpleChanges, ChangeDetectionStrategy, ChangeDetectorRef, OnInit, OnDestroy } from '@angular/core';
import { FormControl } from '@angular/forms';
import { MatCheckboxChange } from '@angular/material';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
@Component({
// tslint:disable-next-line:component-selector
selector: 'mat-select-check',
templateUrl: './mat-select-check.component.html',
styleUrls: ['./mat-select-check.component.css'],
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class MatSelectCheckComponent implements OnChanges, OnInit, OnDestroy {
@Input() selectControl: FormControl;
@Input() values = [];
@Input() text = 'Select All';
@Input() isGroup = false;
@Input() groupData: any;
@Input() dataKey = 'Key';
@Input() isMultiple?: boolean;
private _onDestroy = new Subject<void>();
isCollapsed = false;
constructor(private changeDetectorRef: ChangeDetectorRef) { }
ngOnChanges(changes: SimpleChanges) {
if (changes && changes.values && changes.values.currentValue && changes.values.currentValue.length) {
this.values = changes.values.currentValue.map(z => z[this.dataKey]);
}
setTimeout(() => {
this.changeDetectorRef.detectChanges();
});
}
ngOnInit() {
if (this.selectControl) {
this.selectControl.valueChanges
.pipe(takeUntil(this._onDestroy))
.subscribe(value => setTimeout(() => {
this.changeDetectorRef.detectChanges();
}));
}
}
ngOnDestroy() {
this._onDestroy.next();
this._onDestroy.complete();
}
isChecked(): boolean {
const hasValues = this.selectControl.value && this.values.length && this.selectControl.value.length;
if (hasValues) {
const length = this.selectControl.value.filter(x => this.values.includes(x)).length;
return length > 0 && length === this.values.length;
}
return false;
}
isIndeterminate(): boolean {
const hasValues = this.selectControl.value && this.values.length && this.selectControl.value.length;
if (hasValues) {
const length = this.selectControl.value.filter(x => this.values.includes(x)).length;
return length > 0 && length < this.values.length;
}
return false;
}
toggleSelection(change: MatCheckboxChange): void {
if (change.checked) {
const newValue = this.selectControl.value ? [...this.selectControl.value, ...this.values] : [...this.values];
this.selectControl.setValue(Array.from(new Set(newValue)));
} else {
this.selectControl.setValue(this.selectControl.value.filter(x => !this.values.includes(x)));
}
}
toggleGroup() {
this.isCollapsed = !this.isCollapsed;
this.groupData[this.groupData.findIndex(x => x.key === this.text)].isVisible = !this.isCollapsed;
}
}
这是如何扩展材质选项组件的示例。
参见 stackblitz 演示以及使用示例
组件:
import { ChangeDetectorRef, Component, ElementRef, HostListener, HostBinding, Inject, Input, OnDestroy, OnInit, Optional } from '@angular/core';
import { MAT_OPTION_PARENT_COMPONENT, MatOptgroup, MatOption, MatOptionParentComponent } from '@angular/material/core';
import { AbstractControl } from '@angular/forms';
import { MatPseudoCheckboxState } from '@angular/material/core/selection/pseudo-checkbox/pseudo-checkbox';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
@Component({
selector: 'app-select-all-option',
templateUrl: './select-all-option.component.html',
styleUrls: ['./select-all-option.component.css']
})
export class SelectAllOptionComponent extends MatOption implements OnInit, OnDestroy {
protected unsubscribe: Subject<any>;
@Input() control: AbstractControl;
@Input() title: string;
@Input() values: any[] = [];
@HostBinding('class') cssClass = 'mat-option';
@HostListener('click') toggleSelection(): void {
this. _selectViaInteraction();
this.control.setValue(this.selected ? this.values : []);
}
constructor(elementRef: ElementRef<HTMLElement>,
changeDetectorRef: ChangeDetectorRef,
@Optional() @Inject(MAT_OPTION_PARENT_COMPONENT) parent: MatOptionParentComponent,
@Optional() group: MatOptgroup) {
super(elementRef, changeDetectorRef, parent, group);
this.title = 'Select All';
}
ngOnInit(): void {
this.unsubscribe = new Subject<any>();
this.refresh();
this.control.valueChanges
.pipe(takeUntil(this.unsubscribe))
.subscribe(() => {
this.refresh();
});
}
ngOnDestroy(): void {
super.ngOnDestroy();
this.unsubscribe.next();
this.unsubscribe.complete();
}
get selectedItemsCount(): number {
return this.control && Array.isArray(this.control.value) ? this.control.value.filter(el => el !== null).length : 0;
}
get selectedAll(): boolean {
return this.selectedItemsCount === this.values.length;
}
get selectedPartially(): boolean {
const selectedItemsCount = this.selectedItemsCount;
return selectedItemsCount > 0 && selectedItemsCount < this.values.length;
}
get checkboxState(): MatPseudoCheckboxState {
let state: MatPseudoCheckboxState = 'unchecked';
if (this.selectedAll) {
state = 'checked';
} else if (this.selectedPartially) {
state = 'indeterminate';
}
return state;
}
refresh(): void {
if (this.selectedItemsCount > 0) {
this.select();
} else {
this.deselect();
}
}
}
HTML:
<mat-pseudo-checkbox class="mat-option-pseudo-checkbox"
[state]="checkboxState"
[disabled]="disabled"
[ngClass]="selected ? 'bg-accent': ''">
</mat-pseudo-checkbox>
<span class="mat-option-text">
{{title}}
</span>
<div class="mat-option-ripple" mat-ripple
[matRippleTrigger]="_getHostElement()"
[matRippleDisabled]="disabled || disableRipple">
</div>
CSS:
.bg-accent {
background-color: #2196f3 !important;
}