首页 > 解决方案 > 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为这个循环做类似事情的方法,所以我不必一直调用整个事情。

标签: angularngfor

解决方案


我有一些想法。没有人是完美的:

定制管道

编写自定义管道:

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 asfeature

<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>

推荐阅读