Using comma as a list separator in Angular 2

AngularAngular2 Template

Angular Problem Overview


I want to create a list of items in my template, separated by commas, but I don't want the last item to have a comma:

one, two, three

How do I accomplish this with Angular 2's template syntax?

Angular Solutions


Solution 1 - Angular

I like Eric's answer better (see his comment for a sample Plunker):

<span *ngFor="let item of items; let isLast=last">
   {{item}}{{isLast ? '' : ', '}}
</span>

My original answer was to use the optional index in the NgFor microsyntax:

<span *ngFor="#item of items, #i=index">
   {{item}}{{i === items.length - 1 ? '' : ', '}}
</span>

An alternative is to use just use CSS ::before syntax, as described here: https://stackoverflow.com/a/31805688/215945

Solution 2 - Angular

I think a simpler approach is

<span> {{items.join(", ")}} </span>

Solution 3 - Angular

I have just needed todo this but my value is in an attribute so the marked answer did not work.

Someone may find this helpful :

I used a pipe, I could have built the string up but felt a pipe would be more readable

CLI

ng g p Delimiter

Pipe

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
  name: 'delimiter'
})
export class DelimiterPipe implements PipeTransform {
  transform(value: string, delimiter: string, isLast: boolean)  {
    return !isLast ? value + delimiter : value;
  }
}

View

<div ngFor="let item of items; let isLast=last" 
     [innerHtml]="item | delimiter:', ':isLast">
</div>

I needed some html in my view hence my need to use the attribute, eg

<div ngFor="let item of items; let isLast=last" 
     [innerHtml]="item | safeHtml | delimiter:', ':isLast">
</div>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMark RajcokView Question on Stackoverflow
Solution 1 - AngularMark RajcokView Answer on Stackoverflow
Solution 2 - AngularnikView Answer on Stackoverflow
Solution 3 - AngularSteve DrakeView Answer on Stackoverflow