0

In my Angular application I have a <form> with a <select> field whose options are fetched at runtime from the server. While the HTTP request is pending I show a loading icon placeholder using ngIf/else:

<div class="form-group row">
    <label for="nameInput" class="col-3 col-form-label-sm">Name</label>
    <div class="col">
        <select *ngIf="(listOfNames$ | async) as listOfNames; else loading" 
            id="nameInput" class="form-control form-control-sm" formControlName="name">
            <option *ngFor="let option of listOfNames" [value]="option">{{ option }}</option>
        </select>
    </div>
</div>

<ng-template #loading>
    <div class="form-control form-control-sm">
        <div class="loading-spinner-anim"></div>     
    </div>
</ng-template>

This works great except that it's a common use case for the Observable listOfNames$ to resolve to an empty array and when this happens it shows the #loading template indefinitely because in the *ngIf directive an empty array is falsy so the else is rendered.

How can I rewrite this to show "loading" only while the Observable listOfNames$ is un-completed and to show something else if it resolves to an empty array?

Thanks in advance!

Kyle V.
  • 4,752
  • 9
  • 47
  • 81
  • 1
    Can you just write the condition as `(listOfNames$ | async) as listOfNames && !!listOfNames`? – martin Jun 28 '18 at 14:13
  • @martin I'm not familiar with this `!!` operator -- what would that do? – Kyle V. Jun 28 '18 at 14:27
  • 1
    That's just two boolean negations that in JavaScript turns any value into boolean.https://stackoverflow.com/questions/10467475/double-negation-in-javascript-what-is-the-purpose/10467486 – martin Jun 28 '18 at 14:28
  • @martin I tried adding it: `*ngIf="(listOfNames$ | async) as listOfNames && !!listOfNames; else loading"` and I get an error `[Angular] Parser Error: Unexpected token &&, expected identifier, keyword, or string at column...` – Kyle V. Jun 28 '18 at 14:30
  • Try this *ngIf="(listOfNames$ | async) as listOfNames?.length>0" – Vinod Bhavnani Jun 28 '18 at 14:32
  • @VinodBhavnani I'm getting the same "Unexpected token" error as with the "&&" operator – Kyle V. Jun 28 '18 at 14:40
  • 1
    @KyleV. Anyway, are you sure your Observable emits an empty array? Because when I put `!![]` into console it prints `true` – martin Jun 28 '18 at 14:46
  • @martin You're right, an empty array should never be falsy. I need to investigate. – Kyle V. Jun 28 '18 at 14:48
  • try by checking one more condition (length of array) in *ngIf – MukulSharma Jun 28 '18 at 15:37
  • @martin you were exactly right to suspect an empty array wasn't being returned. My code was throwing an exception inside the `tap()` operator function of the `Observable` and I suspect that was preventing it from ever resolving, leaving my control in the "Loading" state. Thanks! – Kyle V. Jun 28 '18 at 16:25

0 Answers0