【问题标题】:get a particular item inside an array in angular 4以角度 4 获取数组中的特定项目
【发布时间】:2018-06-16 03:19:26
【问题描述】:

在 Angular 视图中,我定义了一个变量 data,如下所示:

[{"name":"science", count: 3},
 {"name":"action", count: 1},
 {"name":"thriller", count: 1},
 {"name":"article",  count: 1},
]

" 因此,在 html 文件中,我想获取名称“科学”或“文章”的计数值

我试过这样:

 <span ng-repeat="item in data| filter: {name: "science"}"> 
    {{ item.count }} 

 </span>

但这没有给出任何东西,我猜是因为过滤器。我怎样才能做到这一点?谁能帮帮我?

【问题讨论】:

  • 如果你实际上使用 Angular 4,那是完全错误的语法。请澄清。
  • 我是新手,所以我还在学习,很抱歉造成混乱
  • 然后花一些时间学习它,例如运行教程:angular.io/tutorial

标签: javascript angularjs


【解决方案1】:

首先,您将混淆 AngularJS (1.x) 语法,对于 Angular (2+),您应该使用 ngFor自定义管道 进行过滤。

 <span> <tr *ngFor="item in data  | sciencefilter:'science'"> {{ item.count }} </span>

你的过滤器应该是

@Pipe({
    name: 'sciencefilter'
})
@Injectable()
export class ScienceFilterPipe implements PipeTransform {
    transform(items: any[], type: string): any {
        return items.filter(item => item.id.indexOf(type) !== -1);
    }
}

不使用过滤器

count :number;

然后,

this.count = this.items.filter(t=>t.name ==='science');

在组件中

 <span> 
    {{ count.length }}
 </span>

【讨论】:

  • 但我想获取不在 for 循环中的特定元素的计数值
  • @pinks 哪个元素?
  • if "name":"science"
  • 看上面的例子
  • 我可以不使用过滤器直接访问数组吗
【解决方案2】:

你可以像这样使用管道 -

import {Injectable, Pipe, PipeTransform} from 'angular2/core';

@Pipe({
    name: 'myfilter'
})
@Injectable()
export class MyFilterPipe implements PipeTransform {
    transform(items: any[], args: any[]): any {
        return items.filter(item => item.id.indexOf(args[0]) !== -1);
    }
}

模板看起来像这样 -

*ngFor="let element of (elements | myfilter:'123')"

【讨论】:

  • 我收到此错误“找不到名称'PipeTransform'”
  • 请浏览文档。该示例可能有一些错误,因为它在发布之前没有经过测试。它只会帮助您提供有关答案的想法。无论如何都要更新答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-12-06
  • 2020-03-30
  • 2022-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-02
相关资源
最近更新 更多