45

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?

2 Answers 2

94

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.

Sign up to request clarification or add additional context in comments.

9 Comments

Glad it helped. Note that this is not specific to Angular, is just a standard JS array method
Yes I can understand that. but it is not a hack? right? it is a right way to do it?
@Simer it's definitely not a hack
It's not a hack, but see the answer below for how you should do it in angular to be more performant.
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
|
66

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>

4 Comments

Should be the accepted answer to be honest, though the example could be more fleshed out.
@crush I put the entire pipe in there. Let me know if you had something else in mind.
Good answer! I would also add pure: true
@YosvelQuintero You could do that. According to the documentation, they are pure by default. That said, sometimes it is better to be more explicit, depending on the needs of the codebase.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.