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?
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With