I have a problem with @if in the Angular template flow syntax.
A value is available in an RxJs Observable. So the async pipe helps and the value is assigned to a variable.
@if (currentPageNumber$ | async; as currentPageNumber) {
// currentPageNumber is number
For value 0 the if statement is not valid. So I exclude only null values… but now the value of currentPageNumber is boolean.
@if ((currentPageNumber$ | async) !== null; as currentPageNumber) {
// currentPageNumber is boolean
How can I check against null but keep my variable with the value of the stream?
3
Answers
Looks like a limitation of the
@if
syntax (0
evaluates to false in JS so you can’t use the syntax), you can just workaround it, by setting the value to string'0'
but you need to take care of converting it back to number using+
Stackblitz Demo
If you are not a fan of having nested if-s in the template you can use the following approach (like the approach shared by jeremy-denis).
Here I’m modifying the response so that it is no longer a "falsy" value, so once the
| async
is evaluated to "truthy" value you will get the block below rendered and you can you theusers
reference to access the number.You can wrap the value directly in the template, this is probably the most straight forward way knowing how the
AsyncPipe
works.