我在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
的方法,所以我不必一直调用整个过程。
您可以创建一个自定义的结构指令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,并且使用的是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>