Angular: Search bar in TypeScript table

陌路散爱 提交于 2019-12-02 01:37:21

I saw that you got your answer... here is another approach for what it is worth... as discussed in the comments...

checkSearchVal() {
    this.USERS = masterUSERS.slice();
    let filteredUsers: User[] = [];
    if (this.searchVal && this.searchVal != '') {

    /* NORMAL FOR
      for(var i=0; i<this.USERS.length; i++ ){
        if(this.USERS[i].firstName.toLowerCase().search(this.searchVal.toLowerCase()) != -1 || this.USERS[i].lastName.toLowerCase().search(this.searchVal.toLowerCase()) != -1 ){
          filteredUsers.push(this.USERS[i])
        }
      }
    */
    /* FOR EACH
      this.USERS.forEach((selectedUser) => {
        if (selectedUser.firstName.toLowerCase().search(this.searchVal.toLowerCase()) != -1 ||
          selectedUser.lastName.toLowerCase().search(this.searchVal.toLowerCase()) != -1) {
          filteredUsers.push(selectedUser);
        }
      })
    */

    /*  FOR OF */
    for (let selectedUser of this.USERS) {
        if (selectedUser.firstName.toLowerCase().search(this.searchVal.toLowerCase()) != -1 ||
          selectedUser.lastName.toLowerCase().search(this.searchVal.toLowerCase()) != -1) {
          filteredUsers.push(selectedUser);
        }
    }

      this.USERS = filteredUsers.slice();
    }
  }

update: moved the this.USERS = filteredUsers.slice(); inside the IF

update:2: same code with forEach and For-Of (to get rid of the TSLint error)

Just create a PIPE.ts file to filter the table:

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

@Pipe({ 
    name: 'filterAll'
})
export class FilterPipe implements PipeTransform {
  transform(value: any, searchText: any): any {
    if(!searchText) {
      return value;
    }
    return value.filter((data) => this.matchValue(data,searchText)); 
  }

  matchValue(data, value) {
    return Object.keys(data).map((key) => {
       return new RegExp(value, 'gi').test(data[key]);
    }).some(result => result);
  }
 }

Add the FilterPipe to app.module.ts in declarations and add this to your component.html:

  <form id="searchForm">
    <div class="form-group">
        <div class="input-group" id="filterAll">
          <div class="input-group-addon"><i class="glyphicon glyphicon-search"></i></div>
          <input type="text" class="form-control" name="searchString" placeholder="Search..." [(ngModel)]="searchString">
        </div>
    </div>
</form>

then you add a pipe to the TR of your table like this:

 <tr *ngFor="let user of users | paginate: {itemsPerPage: pageSize,
                                           currentPage: page,
                                           totalItems: users.length} | filterAll: searchString">

I forgot about the component.ts file sorry: You need to put the searchString variable as:

public searchString: string;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!