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
I think a simpler approach is
<span> {{items.join(", ")}} </span>
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
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>
This is worked for me
<span *ngFor="let item of items; let isLast=last">
{{item}}{{isLast ? '' : ', '}}
</span>