javascript - 将逗号添加到 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>
解决方案
有两种方法可以通过使用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 ? '' : ', ' }}
</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'];
}
希望这会有所帮助!
推荐阅读
- python - 我正在使用 discord.py Rewrite 制作一个机器人,并且检查出现错误,不断返回
- postman - 如何使用 Postman 预请求脚本存储 cookie 值?
- cakephp-3.7 - CakePHP 3 自定义表单
- python - 按列绘制颜色散点图 Plotly
- ios - 在没有 Xcode 的 iPhone 上模拟 GPS 位置
- python - 我怎样才能修复在python中没有定义addr
- xml - 是否可以在不解析其子元素的情况下流式解析 XML 父元素?
- c++ - 从 QAbstractItemModel 中删除项目时 QSortFilterProxyModel 崩溃
- ms-word - 使用 pandoc 将 LaTeX 文档转换为单词——多列表格的问题
- directory - ADA - 使用模式搜索目录 - 没有按应有的方式返回