ngFor - 将 "shortcut" 分配给迭代复杂对象中的变量

ngFor - assign "shortcut" to variable in iterated complex object

我的 Angular 应用程序中有一个 ngFor 循环,我在其中循环访问一组复杂的深层对象。这些复杂对象的深处有一个变量需要定期访问。有没有办法创建一个 "shortcut" 变量,让我可以简单地访问它?

<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 的事情,这样我就不必一直调用整个过程。

您可以创建一个自定义结构指令 appLet,它可以让您定义一个变量。

import {Directive, Input, TemplateRef, ViewContainerRef} from '@angular/core';

interface LetContext<T> {
    appLet: T;
}

@Directive({
  selector: '[appLet]'
})
export class LetDirective<T> {

  private _context: LetContext<T> = { appLet: null };

  @Input()
    set appLet(value: T) {
        this._context.appLet = value;
    }

  constructor(_viewContainer: ViewContainerRef, _templateRef: TemplateRef<LetContext<T>>) {
    _viewContainer.createEmbeddedView(_templateRef, this._context);
  }
}

并在您的模板中像这样使用它

<tr *ngFor="let transaction of transactions;let i=index">
  <td *appLet="transaction.purchase.subscription.customer as customer">
    <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>
</tr>

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

自定义管道

编写自定义管道:

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,并使用 as 特性

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