Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

async pipe as not working within an input in Angular

Tags:

angular

rxjs

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!

like image 460
David Avatar asked Jan 19 '18 08:01

David


People also ask

What type of data works with async pipe in angular?

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.

How does angular async pipe work?

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.

When should I use async pipe angular?

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.


2 Answers

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.

like image 69
martin Avatar answered Oct 23 '22 17:10

martin


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>
like image 2
Makla Avatar answered Oct 23 '22 16:10

Makla