如何在Angular的*ngIf中创建变量避免重复管道调用?
解决方案
在Angular里,你可以通过两种常用方式实现避免重复调用管道的需求:
方式一:使用ng-container做逻辑包裹
ng-container不会生成额外DOM元素,适合用来先完成管道赋值再做后续判断:
<ng-container *ngIf="items | somePipe as pipedItems"> <test-component *ngIf="pipedItems.length" [items]="pipedItems"></test-component> </ng-container>
这里管道只会执行一次,先把处理结果赋值给pipedItems,之后的长度判断和组件传参都直接复用这个变量。
方式二:在组件类中封装逻辑
如果希望模板更简洁,可以把管道调用逻辑移到组件类里,比如定义一个getter:
// 组件类中 import { SomePipe } from './path/to/some.pipe'; constructor(private somePipe: SomePipe) {} get pipedItems() { return this.somePipe.transform(this.items); }
然后模板里直接使用这个getter:
<test-component *ngIf="pipedItems.length" [items]="pipedItems"></test-component>
这种方式同样能保证管道只执行一次,而且把逻辑从模板抽离到了组件层,维护起来更方便。
注意:你最初设想的((items | somePipe) as pipedItems).length写法在Angular模板中不生效,因为as的赋值优先级低于属性访问,所以必须拆分赋值和判断的步骤。
内容的提问来源于stack exchange,提问作者Kvasimodo
相关产品推荐
相关产品推荐

