Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing result of async pipe in template from component code in Angular 2

In Angular 2 I have a component with a template.

In the component TypeScript code i create a Reactive Extensions Observable (items$) and use it in an ngFor-directive in the template with an async-pipe.

This way I do not have to worry about subscribing and unsubscribing myself.

<div *ngFor="let item of items$ | async"></div>
...
</div>

Now from the component code I would like to access the list of items, but without subscribing to it. Is there a way from the template to hand back a copy of or reference to the items list?

like image 461
lox Avatar asked Sep 12 '17 11:09

lox


People also ask

Can I use async pipe in component?

Using AsyncPipe with ObservablesThere is no need to unsubscribe manually in the component. Angular handles subscriptions of async pipes for us automatically using ngOnDestroy. AsyncPipe uses the OnPush change detection out of the box.

What does async pipe return?

Angular's async pipe is a pipe that subscribes to an Observable or Promise for you and returns the last value that was emitted.

What does AsyncPipe do in 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.

How does Angular handle async data?

Solution 1: Use *ngIf Solution one is the easiest. Use *ngIf in blogger component to delay the initialization of posts components. We will bind the post component only if the posts variable has a value. Then, we are safe to run our grouping logic in posts component ngOnInit .


2 Answers

You could just do this in the component:

items$.pipe(tap(items => this.items = items);

This way, you don't subscribe to the stream, and can keep using async pipe, but if a new value is emitted it will be saved in items variable.

like image 134
Pizzicato Avatar answered Oct 18 '22 11:10

Pizzicato


Since Angular 4+ you can use special syntax with as (works for *ngIf as well):

<div *ngFor="let item of items$ | async as items"></div>
  {{ items.length }} ...
</div>

See the example here https://angular.io/api/common/NgForOf

like image 36
martin Avatar answered Oct 18 '22 12:10

martin