为角度材质的<mat-select>组件实现搜索过滤器

时间:2018-01-25 12:22:04

标签: angular angular-material

尝试使用角度材料在角度2中实现一个简单的应用。
我实现了一个带分页的简单表格。

我还使用了mat-select组件,但为此我想实现一个搜索过滤器,从列表中键入并搜索所需的选项。

下面显示的是我的.html文件

<table>
 <tr><td> Department</td>
<td>
  <mat-form-field>
  <mat-select placeholder=" ">
    <mat-option> </mat-option>
    <mat-option *ngFor="let dep of dept" [value]="dep">{{dep}}</mat-option>
  </mat-select>
</mat-form-field><br/>
</td>
</tr>


</table>

<br><br>

<button >Search</button>

<button >Reset</button>

<button >Close</button>


<mat-card>
<div class="example-container mat-elevation-z8">
  <mat-table #table [dataSource]="dataSource">

    <!-- Account No. Column -->
    <ng-container matColumnDef="accno">
      <mat-header-cell *matHeaderCellDef> Account No. </mat-header-cell>
      <mat-cell *matCellDef="let element"> {{element.accno}} </mat-cell>
    </ng-container>

    <!-- Account Description Column -->
    <ng-container matColumnDef="accdesc">
      <mat-header-cell *matHeaderCellDef> Account Description </mat-header-cell>
      <mat-cell *matCellDef="let element"> {{element.accdesc}} </mat-cell>
    </ng-container>

    <!-- Investigator Column -->
    <ng-container matColumnDef="investigator">
      <mat-header-cell *matHeaderCellDef> Investigator </mat-header-cell>
      <mat-cell *matCellDef="let element"> {{element.investigator}} </mat-cell>
    </ng-container>

    <!-- Account CPC Column -->
    <ng-container matColumnDef="accCPC">
      <mat-header-cell *matHeaderCellDef> Account CPC </mat-header-cell>
      <mat-cell *matCellDef="let element"> {{element.accCPC}} </mat-cell>
    </ng-container>

     <!-- Location Column -->
    <ng-container matColumnDef="location">
      <mat-header-cell *matHeaderCellDef> Location </mat-header-cell>
      <mat-cell *matCellDef="let element"> {{element.location}} </mat-cell>
       </ng-container>


 <!-- Client Dept ID Column -->
    <ng-container matColumnDef="cdeptid">
      <mat-header-cell *matHeaderCellDef> ClientDeptID </mat-header-cell>
      <mat-cell *matCellDef="let element"> {{element.cdeptid}} </mat-cell>
       </ng-container>


        <!-- Dept Description Column -->
    <ng-container matColumnDef="depdesc">
      <mat-header-cell *matHeaderCellDef> Dept Description  </mat-header-cell>
      <mat-cell *matCellDef="let element"> {{element.depdesc}} </mat-cell>
       </ng-container>


    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
  </mat-table>

  <mat-paginator #paginator
                 [pageSize]="10"
                 [pageSizeOptions]="[5, 10, 20]">
  </mat-paginator>
</div>
</mat-card>

下面显示的是我的.ts文件

import {Component, ViewChild} from '@angular/core';
import {MatPaginator, MatTableDataSource} from '@angular/material';

@Component({
  selector: 'app-account',
  templateUrl: './account.component.html',
  styleUrls: ['./account.component.scss']
})

export class AccountComponent {



  dept = [
    'Administrative Computer',
    'Agosta Laboratory',
    'Allis Laboratory',
    'Bargaman Laboratory',
    'Bio-Imaging Resource Center',
    'Capital Projects',
    'Casanova Laboratory',
    'Darst Laboratory',
    'Darnell James Laboratory',
    'Deans Office',
    'Energy Consultant',
    'Electronic Shop',
    'Facilities Management',
    'Field Laboratory'
  ];


  displayedColumns = ['accno', 'accdesc', 'investigator', 'accCPC','location','cdeptid','depdesc'];
  dataSource = new MatTableDataSource<Element>(ELEMENT_DATA);

  @ViewChild(MatPaginator) paginator: MatPaginator;

   ngAfterViewInit() {
    this.dataSource.paginator = this.paginator;
  }
}

export interface Element {
  accno: number;
  accdesc: string;
  investigator: string;
  accCPC: string;
  location:string;
  cdeptid: number;
  depdesc: string;
}

const ELEMENT_DATA: Element[] = [
  {accno: 5400343, accdesc: 'ASTRALIS LTD', investigator:'Kruger, James G.', accCPC: 'OR',location:'ON',cdeptid: 110350,depdesc: 'Kruger Laboratory'}

  ];

任何人都可以帮我在我的应用程序中使用mat-select组件实现搜索过滤器吗?

9 个答案:

答案 0 :(得分:3)

顺便说一句。即将发布的一些Angular Material版本可能会支持此功能。讨论已经开放:https://github.com/angular/components/issues/5697

答案 1 :(得分:2)

我找到了搜索下拉值的解决方案

这是html代码

<mat-select class="yourClass" [(ngModel)]="searchObj">
            <input class="yourClass" placeholder ="search " (keyup)="onKey($event.target.value)"> 
            <mat-option *ngIf="someCondition" [value]='Select'>Select</mat-option>
            <mat-option *ngFor="let data of dataArray" [value]="data">{{data}}</mat-option>
          </mat-select>

这是打字稿代码 键功能获取输入值

    onKey(value) { 
            this.dataArray= []; 
            this.selectSearch(value);       
        }

在下拉列表的提供值中执行搜索给定值

selectSearch(value:string){
            let filter = value.toLowerCase();
            for ( let i = 0 ; i < this.meta.data.length; i ++ ) {
                let option = this.meta.data[i];
                if (  option.name.toLowerCase().indexOf(filter) >= 0) {
                    this.dataArray.push( option );
                }
            }
        }

此函数是您的主要搜索函数调用api并获取数据的地方

  

this.meta.data

        searchDpDropdown(){
            for ( let i = 0 ; i < this.meta.data.length; i ++ ) {
                this.dataArray.push( this.meta.data[i] );
            }
        }

答案 2 :(得分:1)

我使用这个https://github.com/bithost-gmbh/ngx-mat-select-search

不幸的是,这是针对Angular 5(但可能有人在这里使用)的Web应用程序,兼容性是:

  • @角/芯:^ 5.0.0 || ^ 6.0.0
  • @ angular / cdk:^ 5.0.0 || ^ 6.0.0
  • @角度/材质:^ 5.0.0 || ^ 6.0.0
  • rxjs:^ 5.5.2 || ^ 6.0.0

这里也正在演示-https://stackblitz.com/github/bithost-gmbh/ngx-mat-select-search-example?file=src%2Fapp%2Fapp.component.ts

答案 3 :(得分:0)

实际上,Angular Material存储库本身为您提供了大量可以激发您灵感的示例。其中一个是表过滤: two-phase-locking

答案 4 :(得分:0)

我发现angular的primefaces有一个多选列表,允许你搜索listitems。它还包括一个内置的全选按钮!你可以在https://www.primefaces.org/primeng/#/multiselect找到它 您可以使用npm install primeng --save

安装primefaces

答案 5 :(得分:0)

即使它的实现不正确,我也为此做了一些工作

component.hml

`

<mat-select formControlName="buyersCountryCode" matInput placeholder="Buyer's Country" required>
                    <input #buyersCountryQuery matInput placeholder="Search"  class="search-input" (keyup)="filterDropDowns(buyersCountryQuery.value, 'BUYERSCOUNTRY')"> 
                    <mat-option *ngFor="let country of filteredBuyersCountry" [value]="country.buyersCountryCode">{{country.buyersCountryValue}}</mat-option>
                </mat-select>

`

component.ts

`

this.filteredBuyersCountry = query
          ? this.filteredBuyersCountry.filter(item =>
              item.buyersCountryValue
                .toLocaleLowerCase()
                .includes(query.toLowerCase())
            )
          : this.dropDowns.buyersCountry;

`

答案 6 :(得分:0)

  

HTML

<h4>mat-select</h4>
<mat-form-field>
  <mat-label>State</mat-label>
  <mat-select>
     <input (keyup)="onKey($event.target.value)"> // **Send user input to TS**
    <mat-option>None</mat-option>
    <mat-option *ngFor="let state of selectedStates" [value]="state">{{state}}</mat-option>
  </mat-select>
</mat-form-field>
  

TS

states: string[] = [
    'Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware',
    'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky',
    'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi',
    'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico',
    'New York', 'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania',
    'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont',
    'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'
  ];

**// Initially fill the selectedStates so it can be used in the for loop** 
selectedStates = this.states; 

**// Receive user input and send to search method**
onKey(value) { 
this.selectedStates = this.search(value);
}

**// Filter the states list and send back to populate the selectedStates**
search(value: string) { 
  let filter = value.toLowerCase();
  return this.states.filter(option => option.toLowerCase().startsWith(filter));
}

解决方案非常简单。 应该像魅力一样工作:)

答案 7 :(得分:-1)

> <mat-form-field>
<mat-label>Items</mat-label>
<mat-select name="item" [(ngModel)]="selected">
  <form>
    <mat-form-field class="w-100">
      <input name="query" type="text" [(ngModel)]="query" matInput>
      <mat-icon matSuffix>search</mat-icon>
    </mat-form-field>
  </form>
  <mat-option>
  </mat-option>
  <mat-option *ngFor="let option of options|appFilter:query" [value]="option">
    {{option.label}}
  </mat-option>
</mat-select>

答案 8 :(得分:-2)

与其自定义MatSelect以便将键入搜索功能添加到选项列表中,不如使用MatAutocomplete

自动完成功能是普通文本输入,由 建议的选项。

HTML:

<form class="example-form">
    <input type="text" placeholder="Search for a street" [formControl]="control" 
 [matAutocomplete]="auto">
         <mat-autocomplete #auto="matAutocomplete">
              <mat-option *ngFor="let street of filteredStreets | async" [value]="street">
      {{street}}
             </mat-option>
         </mat-autocomplete>
</form>

TS

control = new FormControl();
  streets: string[] = ['Champs-Élysées', 'Lombard Street', 'Abbey Road', 'Fifth Avenue'];
  filteredStreets: Observable<string[]>;

  ngOnInit() {
    this.filteredStreets = this.control.valueChanges.pipe(
      startWith(''),
      map(value => this._filter(value))
    );
  }

  private _filter(value: string): string[] {
    const filterValue = this._normalizeValue(value);
    return this.streets.filter(street => this._normalizeValue(street).includes(filterValue));
  }

  private _normalizeValue(value: string): string {
    return value.toLowerCase().replace(/\s/g, '');
  }

引用: Demo (StackBlitz) || Official Docs & Examples