简体   繁体   English

如何使用ngModelChange过滤角度4中的对象值?

[英]How can i filter object value in angular 4 using ngModelChange?

I'm trying to create a input field that filters the list geneated using ngFor, by "description" property name. 我正在尝试创建一个输入字段,以通过“ description”属性名称过滤使用ngFor生成的列表。 The list is an object like this: 列表是这样的对象:

[
 { code: 001, description: "Product 001 description" },
 { code: 002, description: "Product 002 description" },
 { code: 003, description: "Product 003 description" },
 { code: 004, description: "Product 004 description" }
]

My function: 我的功能:

seachFilterData(e) {
    const query = e;
    this.filterData.map((items) => Object.values(items).forEach(value => {
      return Object.keys(value).filter(k => {
        if (value.toLowerCase().includes(query.toLowerCase())) {
          return items;
        }
      });
    }));
  }

the HTML: HTML:

<input type="text" class="tokenfield-search" placeholder="search" [ngModel]="searchFilter" value="" (ngModelChange)="seachFilterData($event)">
<div class="tokenfield-list">
  <ul>
    <li *ngFor="let data of filterData | keys">

When i console.log(items) it's filtering, but the list doesnt change. 当我console.log(items)它正在过滤,但列表没有改变。 Any thoughts? 有什么想法吗?

If you know you only need to filter by description, you can do a compare with indexOf on just that field and filter out as needed. 如果您知道只需indexOf描述进行过滤,则可以仅对该字段与indexOf进行比较,然后根据需要进行过滤。

seachFilterData(e) {
    const query = e;

    // convert to lowercase to do case insensitive search
    const query = e.toLowerCase();

    this.filterData = this.filterData.filter(item => item.description.toLowerCase().indexOf(query) !== -1);
}

If your query is product 001 , your filtered list ( filterData ) will be 如果您的查询是product 001 ,则过滤后的列表( filterData )将是

[
    { code: 001, description: "Product 001 description" }
]

When you run searchFilterData you aren't saving the state. 运行searchFilterData您不会保存状态。

seachFilterData(e) {
    const query = e;
    this.filterData = this.filterData.map((items) => {
      Object.values(items).forEach(value => {
      return Object.keys(value).filter(k => {
        if (value.toLowerCase().includes(query.toLowerCase())) {
          return items;
        }
      }});
    }));
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM