2

I migrated from the structural directives *ngIf and *ngFor to the new control flow with @if and @for in Angular.

But there is one case that I used previously but I cannot seem to get it to work with the new control flow. Tried to find some more information also online but didn't find anything specific on this particular case so I decided to post here.

I used to do:

*ngFor="let option of options$ | async as options"

But neither of these seem to work:

@for(option of options$ | async; as options, track option)
@for(option of options$ | async; as options; track option)
@for(option of (options$ | async; as options); track option)

So I ended up splitting it into an @if and @for combination like so:

@if (options$ | async; as options) {
  @for(option of options) {
    ...
  }
}

But it would be nice to make it work in one line. Is there some valid syntax to make this combination of async pipe and aliasing a variable work?

2
  • 1
    aliasing for @for is currently not supported:github.com/angular/angular/issues/53233 Commented May 29, 2024 at 13:29
  • @Chellappanவ If you post that as an answer I will accept it and close the question. Commented May 29, 2024 at 19:30

2 Answers 2

5

You can just directly use like this, there is no need to define a local variable (options).

@for(option of (options$ | async); track option) {
    <div>{{option.name}}</div>
}

If you require the full options, then I recommend a wrapped if condition, here you can use options variable inside the for loop.

@if (options$ | async; as options) {
    @for(option of options; track option) {
        <div>{{option.name}}</div>
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your answer. I understand there is no need for the alias, but in some cases it is just nice to have the alias (maybe not obvious in this simplified example).
@Wilt Let only allows Unknown "let" parameter variable "(options$ | async)". The allowed variables are: $index, $first, $last, $even, $odd, $count I get this error!
@Wilt Future version of angular will allow you to leverage @let so you can do <div> @let greeting = 'Hello, ' + name + '!'; <h1>{{ greeting }}</h1> </div> @let introduction link
2

As of Angular 18, you can create aliases for @if block , but aliasing @for is not currently supported.

@if (options$ | async; as options) {
  @for(option of options) {
    ...
  }
}

For More Information

1 Comment

Yes, this works well. As I also wrote in my question this is exactly what I ended up using as a workaround.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.