angular - ngFor - 将“快捷方式”分配给迭代复杂对象中的变量
问题描述
我在我的 Angular 应用程序中有一个 ngFor 循环,我在其中迭代了一组复杂的、深层次的对象。在这些复杂对象的深处有一个变量需要定期访问。有没有办法创建一个“快捷方式”变量,让我可以简单地访问它?
<tr *ngFor="let transaction of transactions;let i=index">
<td>
<h5 class="text-dark">{{transaction.purchase.subscription.customer.name}}</h5>
<span *ngIf="transaction.purchase.subscription.customer.is_company" class="text-mute">{{transaction.purchase.subscription.customer.contact_first_name}} {{transaction.purchase.subscription.customer.contact_first_name}}</span>
</td>
</tr>
我想要一种let customer=transaction.purchase.subscription.customer
为这个循环做类似事情的方法,所以我不必一直调用整个事情。
解决方案
我有一些想法。没有人是完美的:
定制管道
编写自定义管道:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'getCustomer'})
export class GetCustomerPipe implements PipeTransform {
transform(transaction: Transaction): Customer {
return transaction.purchase.subscription.customer;
}
}
在你的组件中,使用它:
<tr *ngFor="let transaction of transactions;let i=index">
<td>
<h5 class="text-dark">{{(transaction | getCustomer).name}}</h5>
<span *ngIf="(transaction | getCustomer).is_company" class="text-mute">{{(transaction | getCustomer).contact_first_name}} {{(transaction | getCustomer).contact_first_name}}</span>
</td>
</tr>
因为这个管道是纯的,所以它比组件中的方法具有性能优势。
不必要的 *ngIf
在你的组件中添加一个不必要的 *ngIf,并使用 is as
feature
<tr *ngFor="let transaction of transactions;let i=index">
<ng-container *ngIf="transaction.purchase.subscription.customer as customer">
<td>
<h5 class="text-dark">{{customer.name}}</h5>
<span *ngIf="customer.is_company" class="text-mute">
{{customer.contact_first_name}} {{customer.contact_first_name}}
</span>
</td>
</ng-container>
</tr>
推荐阅读
- angular - 如何使用 Angular 5 处理 https 调用中的服务器端证书
- windows - 安装后,`docker info` 不起作用
- python-3.x - 为 seaborn 的 factorplot boxplot 中的每个框添加标签
- javascript - 如何获取单击的div元素的rowIndex
- sql-server - Microsoft SQL Server 中的 UPDLOCK 是否会阻止插入 IF EXISTS 查询中的键?
- javascript - 用flask发送文件并返回数据而不刷新html页面
- jupyter-lab - Jupyter-Lab,在笔记本的文本编辑器中打开文件
- php - 即使数组包含一件事,也使用数组进行 php 测验
- mysql - 从 MySQL 读取时从 JSON 数组的每个 JSON 对象中过滤掉不需要的字段
- python - 我正在处理银行数据集,我必须只使用“工作经验”列的整数部分