Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass async variable in template (action) function?

I need to pass async variable to the function. Something like this:

<div class="team" (click)="addToFavorite((match | async)?.id)">

And of course I have an error.

Parser Error: Cannot have a pipe in an action expression.

Maybe there is a way to transform async variable in JavaScript?

like image 479
AlexZvl Avatar asked Oct 28 '16 07:10

AlexZvl


3 Answers

Here is how I solved it :

<div *ngIf="(match | async) as match" class="team" (click)="addToFavorite(match.id)">

It's short, simple and it works.

<ng-container *ngIf="(match | async) as match">
   <div class="team" (click)="addToFavorite(match.id)">
   </div>
</ng-container>

Update January 20th 2021

To be more clear I would name match observable source as match$.

And we can now use the new @ngrx/component package and use the new ngrxLet structural directive :

<ng-container *ngrxLet="match$ as match">
  <div class="team" (click)="addToFavorite(match.id)">
  </div>
</ng-container>

The async pipe is no more necessary. More info on ngrx.io, on this link.

like image 68
Benoît Plâtre Avatar answered Nov 02 '22 13:11

Benoît Plâtre


Another option for simple variables and without any observables is writing value of the variable into hidden input:

<div *ngIf="(match | async)?.id">
    <input  #myControl [value]="(match | async).id" type="hidden" />
    <div class="team" (click)="addToFavorite(myControl.value)">
</div>
like image 14
Ilya Loskutov Avatar answered Nov 02 '22 11:11

Ilya Loskutov


You can't do it in template.

But you can:

<div class="team" (click)="addToFavorite()">

and in your .component.ts:

public addToFavorite() {
  this
    .match  // should retain last value (e.g. use BehaviorSubject)
    .first() // completes after passing one value only
    .subscribe(
      (matchValue) => {
        // your logic here
    });
}

Note: We are subscribing (and immediately unsubscribing), similarly async pipe subscribes to Observable.

like image 1
m4js7er Avatar answered Nov 02 '22 11:11

m4js7er