Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to keep the result of a pipe inside a template input variable in Angular 2?

Tags:

angular

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>
like image 838
svi3c Avatar asked Jun 17 '16 13:06

svi3c


1 Answers

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 ;-)

Source

like image 56
golfadas Avatar answered Nov 17 '22 01:11

golfadas