在使用 Angular 模板时,我发现数组函数类似于 slice()
与 ngFor
配合使用绝对没问题像follow这样的指令表达式
<div *ngFor="let item of arry.slice(3)">
{{ item.name }}
</div>
当我尝试使用像 filter()
这样的数组函数时或 map()
在ngFor
喜欢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)]
为了理解这种行为背后的原因,我试图找到一些解释这种限制的文档,但没有找到。任何线索或解释将不胜感激。
最佳答案
如评论中所述,Angular 对模板中允许的表达式类型非常严格。这样做有充分的理由:例如,涉及函数调用的复杂表达式不能很好地用于变化检测。请记住,这些表达式实际上并不是 JavaScript/TypeScript;它们只是 JavaScript-like。
如果你真的想在模板中做这个过滤,那么
<div *ngFor="let item of arry">
<ng-container *ngIf="item.marks > 40">
{{ item.name }}
</ng-container>
</div>
另一种方法是编写一个管道来进行过滤。但是,Angular 团队也不建议这样做。
一般来说,更复杂的逻辑可以也应该写在组件的 TS 逻辑中。
顺便说一句,对于slice
,推荐使用slice pipe . Angular 将能够比 .slice()
更好地优化它。
关于javascript - 为什么像 'filter' 和 'map' 这样的数组函数在 Angular 的 'ngFor' 表达式中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44660605/