I encountered some unexpected behavior with the const
keyword while using it in an Angular 2 *ngFor
loop.
Let's consider the following base code:
interface Foo {
name: string;
list: string[];
}
@Component({ ... })
class FooComponent() {
@Input foo: Foo;
@Input list: string[];
}
Using const
in the template below would work fine during compilation and runtime.
<li *ngFor="const element of list"> ... </li>
However, if we introduce the SlicePipe, using const
will result in a TypeScript compiler error at the |
token.
<li *ngFor="const element of list | slice:0:3"> ... </li>
^ unexpected token
<li *ngFor="let element of list | slice:0:3"><!-- completely fine --></li>
The error occurs because the pipe is applied to the element and not the list when const
is used, which seems a bit strange.
Further complications arise when attempting to iterate over Foo.list
using const
.
<li *ngFor="const element of foo.list"> ... </li>
^ unexpected token
<li *ngFor="let element of foo.list"><!-- completely fine --></li>
So, when should we use const
and why do we need to use let
in these scenarios?