How to pass async variable in template (action) function?
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>
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
.
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.