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

I need to pass an asynchronous variable to a function. Something like that:

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

And of course I have a mistake.

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

Maybe there is a way to convert an asynchronous variable to JavaScript?

+11
source share
5 answers

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

<div *ngIf="(match | async)?.id">
    <input  #myControl [value]="(match | async).id" type="hidden" />
    <div class="team" (click)="addToFavorite(myControl.value)">
</div>
+7
source

Here's how I solved it:

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

It is short, simple, and it works.

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

.

:

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

.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 subscribe (and immediately unsubscribe), similarly the asyncchannel subscribes to Observable.

+2
source

What about:

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

and then in your code:

addToFavorite(obs: Observable<any>) {
  obs.take(1).subscribe(value => {
    addToFavoriteById(value.id);
  });
}
+1
source

It seems you need to use a helper method:

<div class="team" (click)="onClick(match)">
class MyComponent {
  onClick(event) {
    event.then(val => this.addToFavorite(val?.id);
  }
  addToFavorite(val) {
  }
}
0
source

Source: https://habr.com/ru/post/1659147/


All Articles