Async Pipe difference between as and let
Asked Answered
N

1

9

Take these examples :

<ng-container *ngIf="vo$ | async; let vo">

and

<ng-container *ngIf="vo$ | async as vo">

They have the same purpose, getting the latest value of the observable into the variable vo.

But is there any difference between these 2 syntax ?

Neslund answered 25/3, 2022 at 13:37 Comment(0)
B
9

The question is probably more towards how Structural Directive works rather than the Async Pipe. as and let syntax are part of Angular Template syntax that Structural Directive makes use of.

There is no difference from the Angular Template syntax side of things. They are valid syntax of Angular template.

However, they're different in how they would be strongly typed. Take a look at the following code of ng_if.ts from Angular source

/**
 * @publicApi
 */
export class NgIfContext<T = unknown> {
  public $implicit: T = null!;
  public ngIf: T = null!;
}

The Structural Directive author can help the consumers in providing a strongly-typed Context. Since there are as and let, the Context also needs to account for both

  • $implicit allows let to be type-safe
  • ngIf (or the Directive's selector) allows as to be type-safe

Further explanation: $implicit is a special property that allows a consumer of a ng-template to grab the context's implicit data by let someVar

<ng-template let-implicit let-someNamedVar="someNamedVar"></ng-template>

In the case of *ngIf, we can rewrite the <ng-container *ngIf in its long form so we can see how the NgIfContext makes sense

<!-- <ng-container *ngIf="vo$ | async as vo"></ng-container> -->
<ng-template [ngIf]="vo$ | async" let-vo="ngIf">
   <ng-container></ng-container>
</ng-template>

<!-- <ng-container *ngIf="vo$ | async;let vo"></ng-container> -->
<ng-template [ngIf]="vo$ | async" let-vo>
   <ng-container></ng-container>
</ng-template>
Bea answered 25/3, 2022 at 18:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.