简体   繁体   中英

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.

you need to use safe navigation operator ?. in case result is null or undefined elseBlock will be visible

<ng-container *ngIf="results?.length;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>

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM