angulartypescriptangular-pipeangular17

How do I bind the result of an @for to a variable?


In Angular 16 (and earlier) it was possible to use "as" behind a for loop to declare the filtered results as a variable.

Like so:

<div *ngFor="let item of (items | pipe: Query) as results">
{{item}}
</div>

How would I achieve this in angular 17?

I already tried using

@for (let item of (items | pipe: Query) as results; track item.id) {
<div>
{{item}}
</div>
}

but that is not working. I'd like to be able to use my filtered results and store them inside an items array.

Is that possible? Any help would be greatly appreciated!


Solution

  • Collection aliasing (i.e. with the as keyword) is not supported with @for, in the Angular 17 control flow syntax.

    See this issue on GitHub, with the relevant quote here:

    @for as mentioned doesn't support aliasing of the collection.

    The angular migration currently does not, but should, log a warning when as is detected during migration. There is an open issue to fix that.

    As an alternative, if you want an explicit alias, is to extract the results with the pipe in an @if, then use them in the @for. Something like this:

    @if (items$ | async; as results) {
    
    @for (item of results; track item.id) {
    <div>
    {{item}}
    </div>
    }