-3

In Angular view I defined a variable data which is like this:

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

" So in html file I want to get the count count value for name "science" or "article"

I tried like this:

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

 </span>

but this gives nothing, I guess because of the filter. How can I do this? Can anyone help me?

pinks
  • 1
  • 3

2 Answers2

-1

First of all you are mixing up with AngularJS (1.x) syntax, with Angular (2+) you should use ngFor and a custom pipe for filtering.

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

and your filter should be

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

WITHOUT USING FILTER

count :number;

and then,

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

and in component

 <span> 
    {{ count.length }}
 </span>
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
-1

You can use pipe like this -

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);
    }
}

And the template would look like this -

*ngFor="let element of (elements | myfilter:'123')"
planet_hunter
  • 3,866
  • 1
  • 26
  • 39
  • I get this error " Cannot find name 'PipeTransform'" – pinks Jan 06 '18 at 14:45
  • Please go through the documentation. The example might have some bugs as it was not tested before posting. It will just help you providing the idea about the answer. Updating the answer anyway. – planet_hunter Jan 06 '18 at 14:48