I'm used to use the async pipe with "as" in an Angular HTML template to avoid replicating observable subscriptions, like this:
<component *ngIf="(selected$ | async) as selected"></component>
So then I can use "selected" anywhere else in the template.
But then if I try to use it like this, in an input:
<component [param]="(selected$ | async) as selected"></component>
I get an error:
Unexpected token 'as' at column 21 in [categories$ | async as categories]
Any idea why? Thanks!
The async pipe subscribes to an Observable or Promise and returns the latest value it has emitted. When a new value is emitted, the async pipe marks the component to be checked for changes. When the component gets destroyed, the async pipe unsubscribes automatically to avoid potential memory leaks.
Angular's async pipe is a pipe that subscribes to an Observable or Promise for you and returns the last value that was emitted. $observable. subscribe((result) => { // do something with the result here }); Every time a new value is emitted the async pipe will automatically mark your component to be checked for changes.
Angular's async pipe is a tool to resolve the value of a subscribable in the template. A subscribable can be an Observable , an EventEmitter , or a Promise . The pipe listens for promises to resolve and observables and event emitters to emit values.
That's correct, the as
syntax is specific to *ngIf
. It's not a general keyword you can use anywhere in Angular templates.
See https://angular.io/api/common/NgIf and search for NgIfAs
class.
As already martin says as
syntax is specific to *ngIf
. But you can use ng-container
to get results that you want:
<ng-container *ngIf="(selected$ | async) as selected">
<component [param]="selected"></component>
</ng-container>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With