How can I put a comma between elements of an array in *ngFor?

Viewed 1202

I wonder how to put a comma between elements of an array without there being a comma at the end of the line. There are similar questions but my is a bit different because I use the *ngFor directive to display text:

<span *ngFor="let style of styles">
    {{style}} //If I put a comma after the text, there would be a comma at the end of the line after the  
              //last element was displayed
<span>

What would be an approach to solve my problem?

2 Answers

You can use the last value from *ngFor:

<span *ngFor="let style of styles; let last = last">
  {{style}}<ng-container *ngIf="!last">,</ng-container>
<span>

Or you can use the first value from *ngFor:

<span *ngFor="let style of styles; let first = first">
  <ng-container *ngIf="!first">,</ng-container> {{style}}
<span>

the JS approach (or TS in this case) with the join function. this way when your in the template the string will already have commas between the words. for example:

const str = ['one','two','three'];
const newStr = str.join(',');
console.log(newStr);//will output: one,two,three

Angular approach is to use the join function inside the template. for my opinion it's the most readable option

<span>{{styles.join(',')}}</span>
Related