Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle undefined arrays in Angular for different templates?

I am working on a search screen for an application. I figure to have three outcomes in the results section.

  • If the user has not attempted a search, then display nothing.
  • If the user has attempted a search and the array is empty, then display "no results".
  • If the user has attempted a search and the array is not empty, then loop over and display the results.

I can get the empty vs non-empty working just fine:

<ng-container *ngIf="results.length">
    <div class="result" *ngFor="let result of results">
        <a href="link-goes-here">Open Result</a>
        <search-result  [result]="result"></search-result>
    </div>
</ng-container>
<ng-container #elseBlock>
    No Results dude.
</ng-container>

But, when I attempt to mix in a check if results is undefined, it doesn't seem to work properly. I tried to use [ngSwitch], but that doesn't seem to work either. I could just create a boolean variable which is false at first, then set to true once a search is performed, but I'd rather have my array start off as undefined and then get assigned after the first search.

like image 383
michael Avatar asked Jan 21 '26 05:01

michael


1 Answers

This should cover your three outcomes. Assuming results is null or undefined by default, we first check if it exits. If it does, check if it has any values or not. If the user has not searched yet, then the *ngIf will return false and wont render anything.

<ng-container *ngIf="results">
    <ng-container *ngIf="results.length > 0; else elseBlock >
       <div class="result" *ngFor="let result of results">
          <a href="link-goes-here">Open Result</a>
          <search-result  [result]="result"></search-result>
       </div>
    </ng-container>

    <ng-template #elseBlock>
        No Results dude.
    </ng-template>

</ng-container>

like image 82
student dev Avatar answered Jan 22 '26 19:01

student dev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!