如何实现全选角材料下拉角5

时间:2018-08-28 16:54:05

标签: angular typescript angular-material angular5

我正在使用mat-select来显示下拉菜单,我需要在角度下拉菜单中选择所有功能。

下面是我的html

<mat-select formControlName="myControl" multiple (ngModelChange)="resetSelect($event, 'myControl')">
    <mat-option>Select All</mat-option>
    <mat-option [value]="1">Option 1</mat-option>
    <mat-option [value]="2">Option 2</mat-option>
    <mat-option [value]="3">Option 3</mat-option>
</mat-select>

这是我的交易代码

/**
 * click handler that resets a multiple select
 * @param {Array} $event current value of the field
 * @param {string} field name of the formControl in the formGroup
 */
protected resetSelect($event: string[], field: string) {
    // when resetting the value, this method gets called again, so stop recursion if we have no values
    if ($event.length === 0) {
        return;
    }
    // first option (with no value) has been clicked
    if ($event[0] === undefined) {
        // reset the formControl value
        this.myFormGroup.get(field).setValue([]);
    }
}

某些无法正常工作的信息,请帮助或让我以更好的方式进行。

3 个答案:

答案 0 :(得分:1)

使用点击事件,请尝试

Console.WriteLine(consumer.test.Value.Name);

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

答案 1 :(得分: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;
  }
}

答案 2 :(得分:0)

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

有关用法示例,请参见stackblitz Demo

组件:

[ModelBinder(BinderType = typeof(MyModelBinder))]
public class MyModel{
    public string Name{ get; set; }
    public string Age{ get; set; }
}

public class MyModelBinder : IModelBinder{
    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        // whatever model binding you need to do
        bindingContext.Result = ModelBindingResult.Success(new MyModel());

        return Task.CompletedTask;
    }
}

HTML:

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

CSS:

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