【问题标题】:Search in table without pipe Angular 6在没有管道Angular 6的表中搜索
【发布时间】:2019-07-02 14:39:40
【问题描述】:

我正在尝试在不使用任何管道的情况下在表内构建搜索。这就是我现在所拥有的:

.ts

  get filteredArray() {
    if (this.searchValue.length === 0) {
      return this.usersList
    }

    return this.usersList.filter((user) => {
      return (this.searchValue.length > 0 ? this.searchValue.indexOf(user.name) !== -1 : true) || 
      (this.searchValue.length > 0 ? this.searchValue.indexOf(user.group) !== -1 : true) || 
      (this.searchValue.length > 0 ? this.searchValue.indexOf(user.age) !== -1 : true)
    })
  }

  inputClick(searchText) {
    if (searchText != "") {
      this.searchValue.push(searchText)
    } else {
      this.searchValue.splice(0, 1)
    }
  }

.html

<input type="text" [(ngModel)]="searchText" (keyup.enter)="inputClick(searchText)">

<table>
  <thead>
    <tr>
      <td><strong>Name</strong></td>
      <td><strong>Group</strong></td>
      <td><strong>Age</strong></td>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let user of filteredArray">
      <td>{{ user.name }}</td>
      <td>{{ user.group }}</td>
      <td>{{ user.age }}</td>
    </tr>
  </tbody>
</table>

这很好用(如果您在input 中输入一些内容并按回车键,它将出现,如果您删除并按回车键,它将恢复到初始数组)

如您所见,为此我过滤了列表的每个字段:

(this.searchValue.length > 0 ? this.searchValue.indexOf(user.name) !== -1 : true) || 
(this.searchValue.length > 0 ? this.searchValue.indexOf(user.group) !== -1 : true) || 
(this.searchValue.length > 0 ? this.searchValue.indexOf(user.age) !== -1 : true)

我的问题是:如何避免在我的退货声明中填写所有字段?因为在我的数据库中,我有 30 多个字段,并且很难写出 30 个不同的||

另外,如果我写joh而不是john,我该如何修改我的代码,以仍然找到条目?

感谢您的宝贵时间! Here you can see a working snippet of my project

【问题讨论】:

    标签: html angular typescript angular6


    【解决方案1】:

    我会以反应式的方式使用 FormControl,但这不是您所要求的。
    我修改了您的解决方案以获取您的用户属性,并检查您的 searchText 是否与您的用户属性之一中的值匹配。

    See this stackblitz

    【讨论】:

      【解决方案2】:

      您可以编写一个函数来遍历所有字段并检查所有字段。

      containsValue(userObj, searchValue){
          return Object.values(userObj).reduce((prev, cur) => {
              cur = cur.toString();
              return prev || cur.indexOf(searchValue) > -1;
          }, false)
      }
      

      在你当前的函数中使用这个方法

      get filteredArray(){
          ...
          return this.userList.filter((user) => this.containsValue(user, this.searchValue));
      }
      

      编辑: 如果您没有使用 ES2017,则将 Object.values() 更改为 Object.keys() 并获取“cur”值作为 userObj[cur]。 所以对于 pre-es2017:

      containsValue(userObj, searchValue){
          return Object.keys(userObj).reduce((prev, cur) => {
              let temp = userObj[cur].toString();
              return prev || temp.indexOf(searchValue) > -1;
          }, false);
      }
      

      【讨论】:

        猜你喜欢
        • 2019-01-06
        • 2019-04-07
        • 2019-04-23
        • 1970-01-01
        • 2022-06-14
        • 1970-01-01
        • 1970-01-01
        • 2019-05-07
        • 2017-06-09
        相关资源
        最近更新 更多