首页 > 解决方案 > ngFor 中的 let 和 const 修饰符行为细节

问题描述

const我在 Angular 2*ngFor语句中运行了一系列意想不到的修饰符行为。

假设我有以下基本代码:

interface Foo {
    name: string;
    list: string[];
}

@Component({ ... })
class FooComponent() {
    @Input foo: Foo;
    @Input list: string[];
}

在以下模板中使用const在编译时和运行时完全没问题。

<li *ngFor="const element of list"> ... </li>

现在,如果我们使用 SlicePipe,它将const不再工作,并且 TypeScript 编译器会在|标记处引发错误。

<li *ngFor="const element of list | slice:0:3"> ... </li>
                                  ^ unexpected token
<li *ngFor="let element of list | slice:0:3"><!-- completely fine --></li>

我期待管道应用于列表,我能找到const无效的唯一原因是切片应用于元素,而不是列表(这很奇怪吗?)。

Foo.list然而,当尝试使用 const进行迭代时,乐趣就来了。

<li *ngFor="const element of foo.list"> ... </li>
                                ^ unexpected token
<li *ngFor="let element of foo.list"><!-- completely fine --></li>

那我们应该什么时候使用const呢?为什么要let在这些情况下使用?

标签: angulartypescript

解决方案


推荐阅读