11
votes

I am using a custom pipe that filter the array based upon the first alphabet in string of array (phone directory style). Whenever i change the alphabet parameter the pipe return the filtered array and i display it using *ngFor. If no match is found it return empty array and my diplay are is blank.

I want that if pipe return empty array my display area should show a div 'No record found'. How can I do that.

<div *ngIf="currentList.length > 0; else nodata" id="outerContainer">
    <div id="listContainer">
        <div class="listItem" *ngFor="let list of currentList | listFilter : listfilterChar" (click)="openContactList()">
            <div class="listInfo">
              <h3>
                {{list.Name}}
              </h3>
          </div>
    </div>
    <div id="alphabetContainer">
      <p *ngFor="let letter of alphabetArray">
        <span class="alphabetContainer" (click)='setListFiltercharacter($event)'>{{letter}}</span>
      </p>
    </div>
  </div>

In the above code on clicking span.alphabetContainer, the variable listfilterChar is updated with alphabet and pipe filter the array. But if no contact found with matching initial alphabet display area remain blank.

2
Possible duplicate of How to use *ngIf else in Angular?Lafexlos
But I think using another div with negated value is much more readable than this ngIf-else.Lafexlos
hey, where is your else nodata div? in that div you should mention your error. it will execute as if array is not empty or greater than zero it will show {{list.Name}} else nodata div.Hrishikesh Kale
I think the pipe is not directly manipulating currentList array. It returns a new array so currentList.length == 0, not workingraju
Not related but filter/sort pipes are not encouraged in Angular2+Harry Ninh

2 Answers

17
votes

Try this out

<div class="listItem" *ngFor="let list of currentList | listFilter : listfilterChar" (click)="openContactList()">
    <div class="listInfo">
        <h3>
            {{list.Name}}
        </h3>
    </div>
</div>
<div *ngIf="(currentList | listFilter : listfilterChar).length === 0">
    "No record found"
</div>
12
votes

Following this article, a better approach will be to do this:

<ng-container *ngIf=”(currentList | listFilter : listfilterChar) as result”>

  <div *ngFor=”let item of result”>
    {{item}}
  </div>

  <b *ngIf="!result.length">No record found</b>

</ng-container>