让我们想象一下,我有 5 个字符串,其中任何一个都可以填充或留空(它基于用户输入)
我想知道如何用逗号很好地分隔它们。我觉得这个问题一定是微不足道的,但我发现它有效并且并不完全愚蠢的唯一想法是:
// Create a function which return me string of arrays
public getAddress(): string[] {
let result = [];
if (this.application.applicant.city) {
result.push(this.application.applicant.city);
}
if (this.application.applicant.postalCode) {
result.push(this.application.applicant.postalCode);
}
if (this.application.applicant.state && this.application.applicant.state.name) {
result.push(this.application.applicant.state.name);
}
return result
}
// Then somewhere in ngOnInit() just call this method:
this.address = this.getAddress();
在我的模板里面:
<span *ngFor="let item of address; let isLast=last">
{{item}}{{isLast ? '' : ', '}}
</span>
或者经典的JS方式:
<span> {{address.join(", ")}} </span>
而且我仍然觉得这过于复杂。我错过了一些简单的解决方案吗?
感谢您的建议
有一个打字稿函数可以分割一个字符串。它还删除了 ,
this.addres = this.address.split(', '); // this is now an array instead of a string.
编辑
我创建了一个字符串,但其中的 newValue newValue 可以是任何东西。
let string = '';
if() {
string = `${string}, ${newValue}`;
}
这里是一个比你的示例解决方案,你在你的方法中创建地址的字符串并直接在你的html模板中显示它(我认为它比在数组上迭代更简单..)
在你的.ts中:
address : string ;
// Create a function which return me string of arrays
public getAddress(): string {
let result = "";
if (this.application.applicant.city) {
result.push(this.application.applicant.city+",");
}
if (this.application.applicant.postalCode) {
result.push(this.application.applicant.postalCode+",");
}
if (this.application.applicant.state && this.application.applicant.state.name) {
result.push(this.application.applicant.state.name+",");
}
if (result.length !== 0 )
result.substring(0, result.length-1);
return result
}
// Then somewhere in ngOnInit() just call this method:
this.address = this.getAddress();
在您的 HTML 模板中:
<span>{{address}}</span>
希望有帮助:)
const fullAddress = [address.line1, address.line2, address.line3]
.filter(Boolean)
.join(', ');