Search code examples
javascripthtmlangulartypescriptangular-directive

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


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?


Solution

  • 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>