简体   繁体   English

如何在 Angular 中按数组中的属性过滤对象?

[英]How to filter objects by properties in an array in Angular?

I have an element which is an array.我有一个元素,它是一个数组。 I want to show the title of one of this objects by filtering in the array.我想通过在数组中过滤来显示其中一个对象的标题。 Like:像:

<p>{{ element | myFilter:'type':'Type1').title }}</p>

So I tried to create an pipe filter:所以我尝试创建一个 pipe 过滤器:

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

@Pipe({
    name: 'myFilter',
    pure: false
})
export class MyFilterPipe implements PipeTransform {
    transform(items: any[], filter: Object): any {
        if (!items || !filter) {
            return items;
        }
        return items.filter(item => item.title.indexOf(filter.type) !== -1);
    }
}

But that didn't work.但这没有用。

My array:我的阵列:

[
      {
       "type": "Type1",
       "title": "Message 1"
      }, 
      {
       "type": "Type2",
       "title": "Message 2"
      }
]

And what I want to show is the title of type 1. Like:而我要展示的是类型1的标题。比如:

<p>{{ element | myFilter:'type':'Type1').title}}</p>

How to do this in Angular?如何在 Angular 中执行此操作?

Stackblitz 堆栈闪电战

You are passing the data incorrectly into the pipe, also the brackets are placed incorrectly.您将数据错误地传递到 pipe,括号也放置不正确。 You should fix the brackets and just pass the data as a string:您应该修复括号并将数据作为字符串传递:

<p>{{ (element | myFilter: 'Type1').title }}</p>

Also you are filtering your pipe on the wrong property.此外,您还在错误的属性上过滤 pipe。 With the updated data input for the pipe it should simply be:使用 pipe 的更新数据输入,它应该只是:

export class MyFilterPipe implements PipeTransform {
  transform(items: any[], filter: string): any {
    if (!items || !filter) {
      return items;
    }
    return items.find(item => item.type === filter);
  }
}

The way you are passing your filter object to the pipe is incorrect.您将过滤器 object 传递给 pipe 的方式不正确。 You are passing strings.你正在传递字符串。

Use like this:像这样使用:

<p>{{ (element | myFilter: {'type':'Type1'})?.title }}</p>`

Also a ( is missing from the start of your statement还缺少一个(从你的声明开始

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

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