36

I have to display a parse an array inside a json in HTML:

 <p class="personaType">{{cardData.names}}</p>

where names is

names: Array(5) 0:"Person" 1:"Artist" 2:"Performing Artist" 3:"Production Artist" 4:"Visual Artist" 5:"Intermedia Artist"

I want to display names as:

Person, Artist, Performing Artist, Production Artist

Right now it is displaying as (without space):

Person,Artist,Performing Artist,Production Artist

Is there any inbuilt pipe available in angular which can be used to display such data?

Always_a_learner
  • 4,585
  • 13
  • 63
  • 112

2 Answers2

85

You can use Array.prototype.join (notice the white space after the comma)

<p class="personaType">{{cardData.names.join(', ')}}</p>

This will print all the elements in the array, separated by a comma and a white space.

bugs
  • 14,631
  • 5
  • 48
  • 52
  • 2
    Glad it helped. Note that this is not specific to Angular, is just a standard JS array method – bugs May 23 '18 at 11:35
  • Yes I can understand that. but it is not a hack? right? it is a right way to do it? – Always_a_learner May 23 '18 at 11:49
  • 1
    @Simer it's definitely not a hack – bugs May 23 '18 at 11:50
  • Hey, I tried it and got: ERROR TypeError: _v.parent.context.$implicit.se.join is not a function – Roi Sadika Nov 13 '18 at 17:06
  • You've probably calling`join` on something that's not an array – bugs Nov 13 '18 at 17:36
  • 4
    It's not a hack, but see the answer below for how you should do it in angular to be more performant. – Troy Weber Sep 23 '20 at 16:14
  • 2
    This answer an Angular "bad practice" due to running a function directly inside the template html and a pipe should be used instead. See the answer below – Bobby_Cheh Dec 14 '22 at 01:56
  • This is perfectly working. But is there a solution to print only on the element of the array? For example, if in the array names I have many objects like name:[ {firstname: "aaa", Lastname:"bbb"}, {firstname: "ccc", Lastname:"ddd"} ] Is there a way to display only aaa, ccc using interpolation? – NicoESIEA Dec 15 '22 at 09:24
  • This answer is wrong, because Angular's change-detection will always rerun the `.join()`-method. A pipe works a little bit different and don't waste CPU time. – akop Jun 12 '23 at 11:46
51

To minimize the load on your application, you might also consider creating a pipe.

The transform function would look like this:

@Pipe({
  name: 'join'
})
export class JoinPipe implements PipeTransform {
  transform(input:Array<any>, sep = ','): string {
    return input.join(sep);
  }
}

It could look something like this, as far as usage:

<p>{{ cardData.names|join:', ' }}</p>
Troy Weber
  • 897
  • 8
  • 8