首页 > 解决方案 > 将逗号添加到 NgFor 列表的最佳方法

问题描述

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

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

HTML解决方案1:

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

在此处输入图像描述

HTML 解决方案 2

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

也试过这个,但没有奏效:

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

在此处输入图像描述

标签: javascripthtmlangular

解决方案


有两种方法可以通过使用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>

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

}

stackblitz 上的演示

希望这会有所帮助!


推荐阅读