Using comma as a list separator in Angular 2

后端 未结 4 1101
一生所求
一生所求 2020-12-08 18:39

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

相关标签:
4条回答
  • 2020-12-08 18:42

    I think a simpler approach is

    <span> {{items.join(", ")}} </span>
    
    0 讨论(0)
  • 2020-12-08 18:55

    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

    0 讨论(0)
  • 2020-12-08 18:55

    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>
    
    0 讨论(0)
  • 2020-12-08 19:08

    This is worked for me

    <span *ngFor="let item of items; let isLast=last">
    {{item}}{{isLast ? '' : ', '}}
    </span>
    
    0 讨论(0)
提交回复
热议问题