本文介绍了无法过滤使用 Http get in angular 2 访问的 (MatSelect) 中的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用带有输入字段和选择的 Angular Material 创建了一个简单的 Angular 应用.

在我的选择中,我使用来自 accountdetails.json 的 HTTP get 请求访问数据,该请求位于我的资产文件夹中.

我已经为选择应用了搜索过滤器,但是当我输入所需的选项时,列表没有被过滤.

account.component.ts:

import {Component, ViewChild, Inject, OnInit} from '@angular/core';从'@angular/forms'导入{FormControl};从 'rxjs/Observable' 导入 { Observable };导入 'rxjs/add/operator/map';从'@angular/forms'导入{ReactiveFormsModule};从@angular/forms"导入{FormGroup};从@angular/material"导入 {MatPaginator, MatTableDataSource};从 '../accountdetail.service' 导入 { AccountdetailService };@成分({选择器:'应用程序帐户',templateUrl: './account.component.html',styleUrls: ['./account.component.scss']})导出类 AccountComponent 实现 OnInit {过滤文本:字符串;部门:任何;acc_id='':号码;构造函数(私人accdetailservice:AccountdetailService){}/* 表格从这里开始--------------- */displayColumns1 = ['acc_id', 'acc_des', 'investigator', 'CPC','location','dept_id','deptdesc'];dataSource1= new MatTableDataSource(ELEMENT_DATA);应用过滤器(过滤器值:任何){filterValue = filterValue.trim();//去除空格filterValue = filterValue.toLowerCase();//MatTableDataSource 默认为小写匹配this.dataSource1.filter = filterValue;}ngOnInit(){this.accdetailservice.accountdetails().订阅(数据=> {this.departments = 数据;//添加这一行this.dataSource1.data = 数据;});}@ViewChild(MatPaginator) 分页器:MatPaginator;ngAfterViewInit() {this.dataSource1.paginator = this.paginator;}@ViewChild('form') 表单;重启() {this.form.nativeElement.reset()}}const ELEMENT_DATA: 元素[] = [];

account.component.html:

欢迎</mat-toolbar><br/><表格#form><表格><tr><td>帐户 ID<td><mat-form-field><input matInput (keyup)="applyFilter($event.target.value)" placeholder="账户ID" [(value)]="acc_id"></mat-form-field><br/></td>&emsp;&emsp;&emsp;&emsp;<td>部门</td><td><mat-form-field><mat-select style="min-width: 200px;"placeholder="要搜索的类型" [(value)]="部门"><input class="input1" matInput type="text" [(ngModel)]="filtertext" (keyup)="applyFilter($event.target.value)"><mat-option *ngFor="让部门的部门| filter:filtertext " [value]="dep.department" >{{ 部门}}</mat-option></mat-select></mat-form-field></td></tr></表单><br/><br/><button mat-raised-button color="primary" (click)="reset()">重置</button><!-- 表格从这里开始--><垫卡><div class="example-container mat-elevation-z8"><mat-table #table [dataSource]="dataSource1"><!-- 账号栏--><ng-container matColumnDef="acc_id"><mat-h​​eader-cell *matHeaderCellDef>帐户ID.</mat-h​​eader-cell><mat-cell *matCellDef="let element">{{element.acc_id}}</mat-cell></ng-容器><!-- 账户描述栏--><ng-container matColumnDef="acc_des"><mat-h​​eader-cell *matHeaderCellDef>账户描述 </mat-h​​eader-cell><mat-cell *matCellDef="let element">{{element.acc_des}} </mat-cell></ng-容器><!-- 调查员栏--><ng-container matColumnDef="调查员"><mat-h​​eader-cell *matHeaderCellDef>调查员</mat-h​​eader-cell><mat-cell *matCellDef="let element">{{element.investigator}} </mat-cell></ng-容器><!-- 帐户每次点击费用列 --><ng-container matColumnDef="CPC"><mat-h​​eader-cell *matHeaderCellDef>帐户每次点击费用 </mat-h​​eader-cell><mat-cell *matCellDef="let element">{{element.CPC}}</mat-cell></ng-容器><!-- 位置列--><ng-container matColumnDef="location"><mat-h​​eader-cell *matHeaderCellDef>位置</mat-h​​eader-cell><mat-cell *matCellDef="let element">{{element.location}}</mat-cell></ng-容器><!-- 客户部门 ID 列 --><ng-container matColumnDef="dept_id"><mat-h​​eader-cell *matHeaderCellDef>DeptID </mat-h​​eader-cell><mat-cell *matCellDef="let element">{{element.dept_id}}</mat-cell></ng-容器><!-- 部门描述栏--><ng-container matColumnDef="deptdesc"><mat-h​​eader-cell *matHeaderCellDef>部门描述</mat-h​​eader-cell><mat-cell *matCellDef="let element">{{element.deptdesc}}</mat-cell></ng-容器><mat-h​​eader-row *matHeaderRowDef="displayedColumns1" ></mat-h​​eader-row><mat-row *matRowDef="让行;列:displayColumns1;"></mat-row></mat-table><mat-paginator #paginator[页面大小]="10"[pageSizeOptions]="[5, 10, 20]"></mat-paginator>

</mat-card>

filter.pipe.ts:

import { Pipe, PipeTransform } from '@angular/core';@管道({名称:'过滤器'})导出类 FilterPipe 实现 PipeTransform {变换(部门 1:任何,过滤文本:字符串){如果(过滤器文本===未定义){退货部门1;}否则如果(部门1){返回部门1.过滤器(功能(部门){return Department.value.toLowerCase().includes(filtertext.toLowerCase());})}}}

app.module.ts:

import { NgModule } from '@angular/core';从'@angular/platform-b​​rowser' 导入 { BrowserModule };从@angular/platform-b​​rowser/animations"导入 { BrowserAnimationsModule };从'@angular/forms'导入{ReactiveFormsModule};从 './filter.pipe' 导入 { FilterPipe };从'@angular/forms'导入{FormsModule};从'@angular/http'导入{HttpModule};import { AppMaterialModule } from './app-material.module';import { AppRoutingModule } from './app-routing.module';从 './app.component' 导入 { AppComponent };从 './account/account.component' 导入 { AccountComponent };从 './accountdetail.service' 导入 { AccountdetailService };导入'./rxjs-operators';@NgModule({声明: [应用组件,帐户组件,过滤管],进口:[浏览器模块,应用路由模块,反应形式模块,浏览器动画模块,应用材料模块,表单模块,Http模块],提供者:[ AccountdetailService ],引导程序:[AppComponent]})导出类 AppModule { }

最后,我为表单应用了一个重置​​按钮.在我单击 Reset 按钮后,Account ID 输入被重置,但 Department 选择字段不会重置.

解决方案

我得到了答案..

我修改了我的 filter.pipe.ts 如下

import { Pipe, PipeTransform } from '@angular/core';@管道({名称:'过滤器'})导出类 FilterPipe 实现 PipeTransform {变换(值:任何,过滤文本?:任何):任何{if (!value) 返回空值;if (!filtertext) 返回值;filtertext = filtertext.toLowerCase();返回值.过滤器(功能(项目:任何){返回 JSON.stringify(item).toLowerCase().includes(filtertext);});}}

I have created a simple Angular app using Angular Material with an input field and a select.

In my select I am accessing data using HTTP get request from accountdetails.json which is placed in my assets folder.

I have applied search filter for the select, but when i type the required option, the list does not get filtered.

account.component.ts:

import {Component, ViewChild, Inject, OnInit} from '@angular/core';
import { FormControl } from '@angular/forms';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import { ReactiveFormsModule } from '@angular/forms';
import { FormGroup } from '@angular/forms';
import {MatPaginator, MatTableDataSource} from '@angular/material';
import { AccountdetailService } from '../accountdetail.service';

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

export class AccountComponent implements OnInit {

  filtertext: string;
  departments: any;
  acc_id='': number;

  constructor( private accdetailservice: AccountdetailService ) { }


  /* Table Starts here
  ---------------------- */

  displayedColumns1 = ['acc_id', 'acc_des', 'investigator', 'CPC','location','dept_id','deptdesc'];
  dataSource1= new MatTableDataSource<Element>(ELEMENT_DATA);


  applyFilter(filterValue: any) {
    filterValue = filterValue.trim(); // Remove whitespace
    filterValue = filterValue.toLowerCase(); // MatTableDataSource defaults to lowercase matches
    this.dataSource1.filter = filterValue;
  }

  ngOnInit(){
    this.accdetailservice.accountdetails()
    .subscribe(data => {
      this.departments = data;
      // Add this row
      this.dataSource1.data = data;
    });
  }


  @ViewChild(MatPaginator) paginator: MatPaginator;

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

    @ViewChild('form') form;
    reset() {
      this.form.nativeElement.reset()
    }
  }

  const ELEMENT_DATA: Element[] = [];

account.component.html:

<mat-toolbar color="primary" style="width:100%"> WELCOME </mat-toolbar><br/>

<form #form>      
  <table>
    <tr>
      <td> Account ID</td>
      <td>
        <mat-form-field>
          <input matInput (keyup)="applyFilter($event.target.value)" placeholder="Account ID" [(value)]="acc_id">
        </mat-form-field><br/>
      </td>

      &emsp;&emsp;&emsp;&emsp;
      <td>Department</td>
      <td>
        <mat-form-field>
          <mat-select style="min-width: 200px;" placeholder="Type to search" [(value)]="department">
            <input class="input1" matInput type="text" [(ngModel)]="filtertext"         (keyup)="applyFilter($event.target.value)">
            <mat-option *ngFor="let dep of departments  | filter:filtertext  " [value]="dep.department" >
              {{ dep.department }}
            </mat-option>
          </mat-select>
        </mat-form-field>
      </td>
    </tr>
  </table>
</form>
<br/><br/>
<button mat-raised-button color="primary" (click)="reset()">Reset </button>

<!-- Table starts here -->

<mat-card>
  <div class="example-container mat-elevation-z8">

    <mat-table #table [dataSource]="dataSource1">

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

      <!-- Account Description Column -->
      <ng-container matColumnDef="acc_des">
        <mat-header-cell *matHeaderCellDef> Account Description </mat-header-cell>
        <mat-cell *matCellDef="let element">{{element.acc_des}} </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="CPC">
        <mat-header-cell *matHeaderCellDef> Account CPC </mat-header-cell>
        <mat-cell *matCellDef="let element">{{element.CPC}}</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="dept_id">
        <mat-header-cell *matHeaderCellDef> DeptID </mat-header-cell>
        <mat-cell *matCellDef="let element">{{element.dept_id}}</mat-cell>
      </ng-container>


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


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

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

filter.pipe.ts:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'filter'
})
export class FilterPipe implements PipeTransform {

  transform(departments1: any, filtertext: string) {
    if(filtertext=== undefined){
      return departments1;
    } else if(departments1)
    {
       return departments1.filter(function(department){
         return department.value.toLowerCase().includes(filtertext.toLowerCase());

       })   
    }
  }
}

app.module.ts:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { ReactiveFormsModule } from '@angular/forms';
import { FilterPipe } from './filter.pipe';
import { FormsModule } from '@angular/forms';
import { HttpModule} from '@angular/http';

import { AppMaterialModule } from './app-material.module';


import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AccountComponent } from './account/account.component';

import { AccountdetailService } from './accountdetail.service';



import './rxjs-operators';


@NgModule({
  declarations: [
    AppComponent,
    AccountComponent ,
    FilterPipe      
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ReactiveFormsModule,
    BrowserAnimationsModule,
    AppMaterialModule,
    FormsModule ,
    HttpModule   
  ],
  providers: [ AccountdetailService ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Lastly, I have applied a reset button for the form. The Account ID input gets reset after i click the Reset button, but the Department select field doesn't reset.

解决方案

I got answer to this..

I modified my filter.pipe.ts as below

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'filter'
})

export class FilterPipe implements PipeTransform {
    transform(value: any, filtertext?: any): any {

        if (!value) return null;
        if (!filtertext) return value;

        filtertext = filtertext.toLowerCase();

        return value.filter(function (item: any) {
            return JSON.stringify(item).toLowerCase().includes(filtertext);
        });
    }
}

这篇关于无法过滤使用 Http get in angular 2 访问的 (MatSelect) 中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 15:09