Home > database >  Async Pipe difference between as and let
Async Pipe difference between as and let

Time:03-26

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 ?

CodePudding user response:

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>
  • Related