如何在* ngFor中的数组元素之间加上逗号?

问题描述 投票:2回答:2

我想知道如何在数组的元素之间放置逗号,而在行尾没有逗号。有类似的问题,但是我有点不同,因为我使用* ngFor指令显示文本:

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

解决我的问题的方法是什么?

javascript html angular typescript angular-directive
2个回答
4
投票

您可以使用last中的*ngFor值:

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

或者您可以使用first中的*ngFor值:

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

1
投票

另一种选择是退出angular的指令,并用join function将其设为JS(在这种情况下为TS)。这样,当您在模板中时,字符串之间的单词之间已经有逗号了。例如:

const str = ['one','two','three'];
const newStr = str.join(',');
console.log(newStr);//will output: one,two,three
© www.soinside.com 2019 - 2024. All rights reserved.