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?
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.
Angular's async pipe is a pipe that subscribes to an Observable or Promise for you and returns the last value that was emitted.
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.
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 .
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.
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
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