Reputation: 575
I really like the syntax of the *ngFor
directive.
You can iterate over all the elements of an array.
I would like to achieve the same thing with the result of a pipe. For example the async
pipe.
When placing the async
pipe everywhere inside my template where I use a property of the result of an observable, I have a lot of subscriptions going on and my template is cluttered with something like {{(someObservable$ | async)?.propertyName}}
.
Is there a way to simply bind the current result of the pipe to a template input variable like this?
<div let="currentValue = someObservable$ | async">
{{currentValue?.foo}}, {{currentValue?.bar}}
...
</div>
I tried this in combination with *ngIf
, but this does not seem to be a valid template expression:
<div *ngIf="let currentValue = someObservable$ | async">
{{currentValue?.foo}}, {{currentValue?.bar}}
...
</div>
Upvotes: 6
Views: 3100
Reputation: 5521
Yes! As of angular 4+, we can store result of successful *ngIf
, like:
<div *ngIf="userObservable | async; else loading; let user">
Hello {{user.last}}, {{user.first}}!
</div>
<template #loading>Waiting...</template>
If you need same with
*ngFor
, simply wrap it in*ngIf
;-)
Upvotes: 7
Reputation: 657376
There is an open issue to support that https://github.com/angular/angular/issues/2451
Currently it's very limited what can be assigned to a template variable.
exportAs
like <form #f="ngForm">
let i=index
in ngFor
and similar predefined variables in other directivesAs workaround you can execute the expression in a method in the component class and make the result available in a property the view can bind to.
Too much logic in the template is discouraged anyway.
Upvotes: 0