Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Way to add Commas to NgFor List

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>

enter image description here

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>

enter image description here

like image 369
Flash Avatar asked Sep 01 '25 16:09

Flash


1 Answers

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

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>

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'];

}

Demo on stackblitz

Hope this will help!

like image 50
TheParam Avatar answered Sep 04 '25 05:09

TheParam