Javascript 在NgFor列表中添加逗号的最佳方法
我看到了一些可能的解决办法。解决方案1工作正常,但解决方案2只是重复了我的阵列5次Javascript 在NgFor列表中添加逗号的最佳方法,javascript,html,angular,Javascript,Html,Angular,我看到了一些可能的解决办法。解决方案1工作正常,但解决方案2只是重复了我的阵列5次 test: string[]= ['apple', 'banna', 'mango', 'orange', 'pear']; HTML解决方案1: HTML解决方案2 也尝试了这个,但没有成功: // <p *ngFor="let x of test">{{x.join(",")}}</p> 有两种方法可以实现这一点,一种是使用数组的join方法,另一种是使用*ngFor,如下所示 a
test: string[]= ['apple', 'banna', 'mango', 'orange', 'pear'];
HTML解决方案1:
HTML解决方案2
也尝试了这个,但没有成功:
// <p *ngFor="let x of test">{{x.join(",")}}</p>
有两种方法可以实现这一点,一种是使用数组的join方法,另一种是使用*ngFor,如下所示 app.component.html app.component.ts
希望这会有帮助 有两种方法可以实现这一点,一种是使用数组的join方法,另一种是使用*ngFor,如下所示 app.component.html app.component.ts
希望这会有帮助 使用解决方案2,您可以简单地排除*ngFor,并且应该在单个中获得所需的输出。如果您需要多个标记,那么解决方案1更合适。我尝试过,但它没有在屏幕上显示,不确定解决方案2在没有ngFor的情况下为什么工作。请参阅。您可以使用纯js['apple'、'banna'、'mango'、'orange'、'pear']来完成。加入,解决方案1可以是:{{test+isLast?:','}}。使用解决方案2,您可以简单地排除*ngFor,并且应该在单个中获得所需的输出。如果您需要多个标记,那么解决方案1更合适。我尝试过,但它没有在屏幕上显示,不确定解决方案2在没有ngFor的情况下为什么工作。看。你可以用简单的js['apple','banna','mango','orange','pear']来完成。加入,解决方案1可以是:{{test+isLast?:','}}。它将是一个来自服务的对象,所以我可能需要一个Ng。在你的例子中,你可以简单地添加test.join“,”for spacingcheck update stackblitz这里啊,看来我的问题是test的定义方式。任何我不能这样定义它的线索:test:string[]=['apple','banna','mango','orange','pear'];与此相反:测试=[‘苹果’、‘香蕉’、‘芒果’、‘橘子’、‘梨’];这也是定义数组的正确方法。即使我更新了stackblitz与相同的,它的工作!这将是一个来自服务的对象,所以我可能需要一个Ng。在你的例子中,你可以简单地添加test.join“,”for spacingcheck update stackblitz这里啊,看来我的问题是test的定义方式。任何我不能这样定义它的线索:test:string[]=['apple','banna','mango','orange','pear'];与此相反:测试=[‘苹果’、‘香蕉’、‘芒果’、‘橘子’、‘梨’];这也是定义数组的正确方法。即使我更新了stackblitz与相同的,它的工作!
<p *ngFor="let x of test">{{test.join(",")}}</p>
// <p *ngFor="let x of test">{{x.join(",")}}</p>
<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>
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'];
}