2

The following structural directive will subscribe to the named observable and assign the locally scoped variable srl to the value. The content only gets rendered when the result is truthy.

<ng-container *ngIf="searchResultLength$ | async as srl">
    (search results goes here)
</ng-container>

But what is the syntax if I want to have some other type of logical operator? What I want to do is:

<ng-container *ngIf="(searchResultLength$ | async as srl) > 2">
   (search results IF there are more than 2 goes here)
</ng-container>

Which looks to me like it should the correct syntax but is rejected by the compiler. I can't find the document for how the as keyword is parsed. Can someone clue me in what the correct syntax should be?

Also, a link to the relevant documentation would help. Doing searches for the as keyword is as futile as it gets.

1
  • Perhaps (searchResultLength$ | async as srl).length > 2 Commented Mar 31, 2020 at 22:34

2 Answers 2

5

That is, in fact, not the correct syntax. The correct syntax for ngIf is

<div *ngIf="condition as value">{{value}}</div>

The as syntax can only be used after the entire ngIf condition and stores the value that the condition evaluates to.

Here is an alternative.

<ng-container *ngIf="searchResultLength$ | async as srl">
  <ng-container *ngIf="srl > 2">
    (search results IF there are more than 2 goes here)
  </ng-container>
</ng-container>
Sign up to request clarification or add additional context in comments.

1 Comment

I had thought of that but was hoping to have only a single *ngIf evaluation. I'll mark this as the answer if nothing better comes up.
1

Here is another solution (not really practical but working :)) using *ngFor and slice pipe:

<ng-container *ngFor="let srl of [length$ | async] | slice : (length$ | async) <= 2"> 
  (search results IF there are more than 2 goes here)
  <br>
  searchResultLength$ = {{ srl }}
</ng-container>

in order not to subscribe twice to length$, use it with piped shareReplay() operator. I also added tap with console.log to verify that we are subscribing only once although using async pipe twice:

length$ = new BehaviorSubject(3).pipe(tap(console.log), shareReplay());

STACKBLITZ: https://stackblitz.com/edit/angular-7pkcnr?file=src%2Fapp%2Fapp.component.ts

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.