admin管理员组

文章数量:1279007

I've seen some possible solutions. Solution 1 works fine but with solution 2 it just repeated my array 5 times.

test: string[]= ['apple', 'banna', 'mango', 'orange', 'pear'];

HTML Solution 1:

<p *ngFor="let x of test; let isLast=last">{{test}} {{isLast ? '' : ','}}</p>

HTML Solution 2

<p *ngFor="let x of test">{{test.join(",")}}</p>

also tried this and did not work:

// <p *ngFor="let x of test">{{x.join(",")}}</p>

I've seen some possible solutions. Solution 1 works fine but with solution 2 it just repeated my array 5 times.

test: string[]= ['apple', 'banna', 'mango', 'orange', 'pear'];

HTML Solution 1:

<p *ngFor="let x of test; let isLast=last">{{test}} {{isLast ? '' : ','}}</p>

HTML Solution 2

<p *ngFor="let x of test">{{test.join(",")}}</p>

also tried this and did not work:

// <p *ngFor="let x of test">{{x.join(",")}}</p>

Share Improve this question edited Mar 14, 2019 at 14:09 TheParam 10.6k4 gold badges43 silver badges54 bronze badges asked Mar 14, 2019 at 13:59 FlashFlash 1,0145 gold badges26 silver badges47 bronze badges 5
  • 1 With solution 2 you can simply exclude the *ngFor and you should get the desired output in a single <p>. If you need multiple <p> tags then solution 1 is more appropriate – Jonathan Seed Commented Mar 14, 2019 at 14:02
  • I tried that and it did not render on the screen, Not sure why – Flash Commented Mar 14, 2019 at 14:05
  • 1 The solution 2 works without ngFor. See this stackblitz. – Martin Parenteau Commented Mar 14, 2019 at 14:15
  • 1 you can do it with plain js ['apple', 'banna', 'mango', 'orange', 'pear'].join(", ") – manish Commented Mar 14, 2019 at 14:17
  • 1 Solution 1 could be: {{test + (isLast ? '' : ', ')}}. – Martin Parenteau Commented Mar 14, 2019 at 14:51
Add a ment  | 

1 Answer 1

Reset to default 13

There two way you can achieve this by using join() method of the array and using *ngFor like below

app.ponent.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>

app.ponent.ts

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

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

}

Demo on stackblitz

Hope this will help!

本文标签: javascriptBest Way to add Commas to NgFor ListStack Overflow