I am working on a search screen for an application. I figure to have three outcomes in the results section.
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.
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>