Search code examples
angularngforangular-ng-if

Angular "include" for Empty results


I want to show a HTML

tag for only 1 time inside a ngFor loop with an ngIf condition for Empty results.

<div *ngFor="let ndata of newsData; let i= index" (click)="redirect(ndata?.url)">
      <div class="news-cont" *ngIf="ndata.title.toLowerCase().includes(searchParam.toLowerCase())">
       <div class="row">
         <div class="col-md-2">
           <img class="m-img" src="{{ndata?.imageurl}}">
         </div>
         <div class="col-md-10">
           <h5> <img class="ic-img" src="{{ndata?.source_info?.img}}"> {{ndata?.source_info?.name}}</h5>
           <h4> {{ndata?.title}}</h4>
           <h6><i class="pe pe-7s-clock"></i> {{ndata?.published_on * 1000 | date:'HH:mm | yyyy-MMM-dd'}} </h6>
           <hr>
           <p [innerHTML]="ndata?.body">  </p>
           <p><i class="pe pe-7s-ribbon"></i>  <span class="categories-tag">Catergories <span>{{ndata?.categories}}</span></span> </p>
         </div>
       </div>
      </div>
        <p ANYCONDITION > No Results</p>
      </div>

I have tried with other condition but for loop iterates it for each entry. Expecting a good solution for this.


Solution

  • Wrap with <ng-template>:

    <ng-template [ngIf]="something.length > 0" [ngIfElse]="noDataTemplate">
      <div *ngFor="let ndata of newsData; let i= index" (click)="ndata && redirect(ndata.url)">
        <!-- your code here -->
      </div>
    </ng-template>
    
    <ng-template #noDataTemplate>
      <div>No data to display</div>
    </ng-template>
    

    This approach will clearly identify what should be done in case of empty data and non-empty data.