Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Angular2 *ngFor iteration, how do I output only unique values from the array?

Tags:

angular

Does it have a built in pipe to do so?

data = [
  {id: 5, name: 'Roger'},
  {id: 5, name: 'Mark'},
  {id: 5, name: 'Zach'},
  {id: 5, name: 'Mark'},
  {id: 5, name: 'Roger'},
];

<ul>
  <li *ngFor="let datum of data">
    {{datum.name}}
  </li>
</ul>

Output

  • Roger
  • Mark
  • Zach
  • Mark
  • Roger

Desired Output

  • Roger
  • Mark
  • Zach
like image 794
anonym Avatar asked Jan 26 '17 05:01

anonym


People also ask

Which is the correct statement to fetch the index value in * ngFor?

Declare a variable inside *ngFor directive using let or as keyword. for instance say indexofelement or simply i . Assign the variable value to index .

What is the purpose of * In ngFor in Angular?

The *ngFor directive is used to repeat a portion of HTML template once per each item from an iterable list (Collection). The ngFor is an Angular structural directive and is similar to ngRepeat in AngularJS. Some local variables like Index, First, Last, odd and even are exported by *ngFor directive.

What is NgForOf?

ngForOf: NgIterable<T> : The value of the iterable expression. Useful when the expression is more complex then a property access, for example when using the async pipe ( userStreams | async ). index: number : The index of the current item in the iterable.

Can we use two ngFor?

We can nest muliple NgFor directives together. We can get the index of the item we are looping over by assigning index to a variable in the NgFor expression.


1 Answers

You can create your own pipe.

import { Pipe, PipeTransform } from '@angular/core';
import * as _ from 'lodash'; 

@Pipe({
  name: 'unique',
  pure: false
})

export class UniquePipe implements PipeTransform {
    transform(value: any): any{
        if(value!== undefined && value!== null){
            return _.uniqBy(value, 'name');
        }
        return value;
    }
}

You need to add in the component the UniquePipe and than add in the HTML file the pipe.

<ul>
  <li *ngFor="let datum of data | unique">
    {{datum.name}}
  </li>
</ul>
like image 196
Yoav Schniederman Avatar answered Sep 21 '22 21:09

Yoav Schniederman