如何在角度材质下拉角度5中实现全选

问题描述 投票:0回答:4
angular typescript angular-material angular5
4个回答
9
投票

使用点击事件试试这个

<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([]);
    }
}

示例:https://stackblitz.com/edit/angular-czmxfp


1
投票

我扩展了 Angular Material 的 MatSelect 以包含以下功能:

  • 搜索
  • 分组
  • 全选
  • 选择组下的所有选项

工作示例可以在 StackBlitz 上找到,完整的存储库可以在 GitHub

上找到

以下是“全选”实现的代码片段

HTML

<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>

TS

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;
  }
}

0
投票

这是如何扩展材质选项组件的示例。

参见 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;
}

0
投票

发表了一篇关于它的文章:https://angular-material.dev/articles/mat-select-all

© www.soinside.com 2019 - 2024. All rights reserved.