Angular 通过对数组的对象施加特定条件,在模板文件中显示特定值
我有一个对象数组,我想从中在html文件上显示特定的文本 条件是:Angular 通过对数组的对象施加特定条件,在模板文件中显示特定值,angular,angular6,Angular,Angular6,我有一个对象数组,我想从中在html文件上显示特定的文本 条件是: 如果用户订阅,则显示文本“自动” 如果未验证用户,则文本“试用” 如果用户已验证并订阅,则文本“免费” 如果用户订阅已结束,则文本“过期” 如果用户订阅由管理员扩展,则文本为“手动” 对于订阅,我在数据库中管理名为payment_details的数组。 对于在数据库中调用的已验证管理布尔字段 我无法在前端为这些创建条件。所以我试着用ts文件。但它正在获取数组的最后一个元素 模板文件: <tr class="table-ro
<tr class="table-rows-customized" *ngFor="let therapist of therapistlist | filter : searchText" >
<td class="td-data pointer" (click)="therapistdetails(therapist._id);">
<img *ngIf="!therapist.profilepic" src="assets/img/users/user.jpg" class="user-image" alt="">
<img *ngIf="therapist.profilepic" [src]="therapist.profilepic" class="user-image" alt="">
{{ therapist.fullname }}
</td>
<td class="td-data">{{ type.id === therapist._id ? type.text : '' }}
</td>
</tr>
this.therapistlist.map((therapist) => {
if(therapist.payment_details) {
if(therapist.payment_details.length && therapist.verifiedBadge) {
this.type = {
text: 'free',
id: therapist._id
}
}
if(therapist.payment_details.length) {
if(therapist.payment_details[0].paymentType == 'Cash') {
this.type = {
text: 'manual',
id: therapist._id
}
}
if(therapist.payment_details[0].paymentType == 'Credit Card') {
this.type = {
text: 'auto',
id: therapist._id
}
}
}
}
if(moment(therapist.premimumEndDate).isAfter(moment())) {
this.type = {
text: 'expired',
id: therapist._id
}
}
})
console.log('map.... ', this.type);
从上面的代码中我没有得到任何东西,在日志中我得到的是空值。map函数将遍历数组中的每个元素,并根据您的条件计算类型。 但是您的console.log在迭代器之外,它将始终获取数组中最后一项的类型 您需要在.map函数中分配和记录类型对象,或者根据需要使用类型对象。这样,您将拥有初始数组中每个对象的特定类型
this.therapistlist.map((therapist) => {
this.type = {
id: therapist._id,
text: 'default'
}
if (therapist.payment_details) {
if (therapist.payment_details.length && therapist.verifiedBadge) {
this.type.text = 'free';
} else if (therapist.payment_details.length) {
if(therapist.payment_details[0].paymentType === 'Cash') {
this.type.text = 'manual';
} else if (therapist.payment_details[0].paymentType === 'Credit Card') {
this.type.text = 'auto';
}
}
}
if (moment(therapist.premimumEndDate).isAfter(moment())) {
this.type.text = 'expired';
}
console.log(this.type);
});
我还重构了您的代码,因为其中一个条件是重叠的
如果第一个条件得到满足,那么第二个条件也会得到满足
if(therapist.payment_details.length && therapist.verifiedBadge)
if(therapist.payment_details.length)
最后,正如现在一样,如果订阅过期,无论类型是什么,它都会更改类型。谢谢@Samuel的回答。我只是把你的代码粘贴到我的代码里。我只得到{id:“id of user”,text:“default”}并将其打印到数组长度。@JaynaTanawala好的,这意味着不满足任何条件。您应该使用更多日志进行调试,并了解原因。您必须检查对象数组中的数据。难道不能从头开始检查吗?