As developers, sometimes we need to render a list and let the user the ability to add more values to the list.

But many times we need to limit the list to be only with unique values.

For example, imagine that the user fills a form where he needs to send an email to other users, we want the emails to be unique.

In Angular js you probably implement this something like this:

This code is fine, but with Angular 2 we can do better. We can use the new Set object introduced in ECMAScript2015 with the ngFor directive.

Set objects are collections of values. You can iterate through the elements of a set in insertion order. A value in the Set may only occur once; it is unique in the Set’s collection.

Let’s see this in action:

Fun stuff!

What? How? Why?

The ngFor directive accepts any object that implements the Iterable interface. You can read more about iterators here.

So, for example, we can create our own iterable and just give it to the ngFor directive.

And it just works.

But, wait, I was lying, not every object that implements the iterator interface. After digging into the source code I found this function:

From this function we can learn that we can’t ngFor on:

String. Map. An object that is not Array.

By the way, the QueryList object is also iterable and works with ngFor .

That’s all!

☞ Please tap or click “︎❤” to help to promote this piece to others.