将逗号添加到NgFor列表的最佳方法

Fla*_*ash 0 html javascript angular

我已经看到了一些可能的解决方案。解决方案1可以正常工作,但是在解决方案2中,它仅重复了我的数组5次。

test: string[]= ['apple', 'banna', 'mango', 'orange', 'pear'];
Run Code Online (Sandbox Code Playgroud)

HTML解决方案1:

<p *ngFor="let x of test; let isLast=last">{{test}} {{isLast ? '' : ','}}</p>
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

HTML解决方案2

<p *ngFor="let x of test">{{test.join(",")}}</p>
Run Code Online (Sandbox Code Playgroud)

也尝试了这个,没有用:

// <p *ngFor="let x of test">{{x.join(",")}}</p>
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

The*_*ram 6

您可以通过以下两种方法使用join()数组的方法和使用*ngFor类似的方法来实现此目的

app.component.html

<h1>String Array Demo</h1>

<h2>Solution 1 - Using  <code> join() </code> method</h2>

<p>{{test.join(', ')}}</p>

<h2>Solution 2 Using <code> *ngFor </code> directive </h2>

<span *ngFor="let x of test; let i = index">
  {{x}} {{i === test.length -1 ? '' : ',&nbsp;' }}
</span>
Run Code Online (Sandbox Code Playgroud)

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
  test: string[] = ['apple', 'banna', 'mango', 'orange', 'pear'];

}
Run Code Online (Sandbox Code Playgroud)

演示在stackblitz

希望这会有所帮助!