为什么像 'filter' 和 'map' 这样的数组函数在 Angular 的 'ngFor' 表达式中不起作用?

Why array functions like 'filter' and 'map' doesn't work in 'ngFor' expression of Angular?

在使用 angular 模板时,我发现像 slice() 这样的数组函数在像 follow

这样的 ngFor 指令表达式中工作得非常好
<div *ngFor="let item of arry.slice(3)">
  {{ item.name }}
</div>

当我尝试在 ngFor 表达式中使用像 filter() or map() 这样的数组函数时,就像 follow

<div *ngFor="let item of arry.filter(i => i.marks > 40)">
  {{ item.name }}
</div>

它给我 angular 模板解析错误

Zone: <root> ; Task: Promise.then ; Value: Error: Template parse errors: Parser Error: Bindings cannot contain assignments at column 25 in [let item of arry.filter(i => i.marks > 40)]

为了理解这种行为背后的原因,我试图找到一些解释这种限制的文档,但找到了 none。任何线索或解释将不胜感激。

如评论中所述,Angular 对模板中允许的表达式类型有相当的限制。这样做有充分的理由:例如,涉及函数调用的复杂表达式不能很好地用于变化检测。请记住,这些表达式实际上并不是 JavaScript/TypeScript;他们只是JavaScript-喜欢.

如果你真的想在模板中做这个过滤,那么

<div *ngFor="let item of arry">
  <ng-container *ngIf="item.marks > 40">
    {{ item.name }}
  </ng-container>
</div>

另一种方法是编写一个管道来进行过滤。但是,Angular 团队也反对这样做。

一般来说,更复杂的逻辑可以也应该写在组件中的 TS 逻辑中。

顺便说一句,对于slice,建议使用slice pipe。 Angular 将能够比 .slice().

更好地优化它

有些相关:Support arrow functions in template syntax.