7

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?

1
  • I think now it not possible that... you will have to make a subscriptions on the .ts and store the result in a variable... Commented Sep 12, 2017 at 14:35

2 Answers 2

11

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

3 Comments

Yes, but I would like a reference to the entire list of items, and would like to access it in the component code (ts-file)
Then no, you'll need to make the subscription in the component.
Actually you can: check this stackoverflow.com/a/57199847/651555

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.