【问题标题】:search filter not filtering based on string input in angular 2搜索过滤器不根据角度 2 中的字符串输入进行过滤
【发布时间】:2017-09-29 13:31:50
【问题描述】:

我想根据一些细节过滤用户列表。用户列表是根据表单中提交的数据生成的。并且用户列表使用*ngFor 显示在视图中。

我想根据搜索输入框中的查询字符串过滤用户列表。为此,我创建了一个自定义管道,它采用搜索框字符串并将其与 usersList 数组进行比较。

但是当我输入搜索字符串时,视图中的用户列表变为空白。

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

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

      transform(value: any, filterString: string, propName: string): any {
        if (value.length === 0) {
          return value;
        }
        const resultArr = [];
        for (const item of value) {
          if (item[propName] === filterString) {
            resultArr.push(item);
          }
        }
      }

    }

// app component.ts

import { Component, OnInit, Input, ViewChild } from '@angular/core';
import { DropDownService } from './services/drop-down.service';
import { IPersonModel } from './interface/person-model';
import { InputDataService } from './services/input-data.service';
// FormBuilder imported from anuglar/forms
import { FormGroup, FormBuilder, Validators } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [DropDownService, InputDataService]
})
export class AppComponent implements OnInit {
  courseForm: FormGroup;
  personDetail: IPersonModel;
  dropDownArr = [];
  selectedOption = null;
  personsList: IPersonModel[] = [];
  courseStat = '';


  constructor(public dropdown: DropDownService, public fieldData: InputDataService, private fb: FormBuilder) {
  }
  onSubmit(): void {
    // adds the user submited data to personDetail object
    this.personDetail.chosenCourse = this.selectedOption;
    this.personDetail.name = this.courseForm.value.username;
    this.personDetail.email = this.courseForm.value.email;
    this.personDetail.address = this.courseForm.value.address;
    this.personDetail.date = this.courseForm.value.date;
    this.fieldData.setPersonData({ ...this.personDetail });
    this.personsList.push({ ...this.personDetail });
    console.log({ ...this.personDetail });
    this.courseForm.reset();
    console.log(this.personsList);
    console.log(this.courseForm);
  }


  // resets the form on clicking the reset button
  resetForm(): void {
    this.courseForm.reset();
  }
  // sets the dropdownlist values on intialization
  ngOnInit() {
    // form controls validation specicified in the class for the Reactive Forms
    this.courseForm = this.fb.group({
      username: [null, [Validators.required, Validators.pattern(/^[a-z0-9_-]{3,16}$/)]],
      email: [null, [Validators.required, Validators.pattern('([a-zA-Z0-9_.-]+)@([a-zA-Z0-9_.-]+)\\.([a-zA-Z]{2,5})')]],
      address: [null, [Validators.required, Validators.minLength(10), Validators.maxLength(100)]],
      date: [null, [Validators.required]],
      select: [null, [Validators.required]]
    });
    this.dropDownArr = this.dropdown.getData();
    // this.personDetail = {
    //   name: '',
    //   email: '',
    //   address: '',
    //   chosenCourse: ''
    // };
    this.personDetail = this.fieldData.getPersonData();
    console.log(this.courseForm);
  }

}

// component Html
 <div class="panel panel-default">
    <div class="panel-heading">Registered users</div>
    <input type="text" [(ngModel)]='courseStat' placeholder="filter based on course">

    <!-- List group -->
    <ul class="list-group">
      <!-- pipes transforms the username's first word by capitalize it-->
      <li class="list-group-item" *ngFor="let person of personsList | filter:personsList:courseStat:'chosenCourse'">username:&nbsp;&nbsp;{{person.name | capitalize}} &nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;&nbsp; email:&nbsp;&nbsp;{{person.email}}
        &nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;&nbsp; DOB: &nbsp;&nbsp;{{person.date | date: 'd/M/y'}} &nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;&nbsp;Address:
        &nbsp;&nbsp;{{person.address}} &nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;&nbsp; Course Chosen: &nbsp;&nbsp;{{person.chosenCourse
        | uppercase}}</li>
    </ul>
  </div>

【问题讨论】:

  • 您的过滤器有两个参数? filter:courseStat:'chosenCourse',方法好像有三个
  • 我将 personList 数组传递给第三段,但它仍然无法正常工作

标签: angular typescript ecmascript-6 angular-forms


【解决方案1】:

你像下面这样更新你的变换,

transform(value: any, filterString: string, propName: string): any {
   
    if (value.length === 0 || !filterString || !propName) {
      console.log(filterString);
      return value;
    }
   
    return value.filter(_person => {
      return _person[propName] === filterString;
    })
}

在 HTML 中,

 <li class="list-group-item" *ngFor="let person of personsList | filter:courseStat:'chosenCourse'">

你写过滤器的方式不对。

查看Plunker!!

【讨论】:

  • 你能解释一下吗?以及如何在过滤器参数中添加要过滤的PersonsListarray
  • 检查更新的答案,您不需要显式传递列表,您只需传递过滤列表所需的参数,因此 transform 方法的第一个参数通过 angular 传递您的值在这种情况下,您的人员列表已应用管道,然后参数正在传递,您可以阅读更多关于相同的here,干杯!!
  • 角度文档中似乎没有解释.filter。你能解释一下这部分吗return value.filter(_person =&gt; { return _person[propName] === filterString; }
  • .filter 它是 Javascript Array 对象上的一个方法,用于过滤任何数组,它与 Angular 无关,您可以在 MDNW3C 上阅读更多相关信息... !!
猜你喜欢
  • 1970-01-01
  • 2016-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-10
相关资源
最近更新 更多