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
1 Answer
Reset to default 13There 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 ? '' : ', ' }}
</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
版权声明:本文标题:javascript - Best Way to add Commas to NgFor List - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741239580a2363706.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论