Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using *ngIf along with angular4 custom pipes

Tags:

angular

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.

like image 829
raju Avatar asked Jan 09 '18 05:01

raju


People also ask

Can we use pipes in ngIf?

Use the async pipe with ngIf We above example uses the async pipe with interpolation. We can also use it with the ngIf or ngFor etc. The following example shows how NOT to use the observable with ngIf directive. The condition (obsValue | async) becomes true , when the observable returns a value.

Can we use async in ngIf?

If you are waiting for asynchronous data, the object can be undefined. In this case, you can use ngIf and store the result of the condition in a local variable as shown in the following example. This code uses only one AsyncPipe , so only one subscription is created.

Can we use multiple pipes in Angular?

Angular Pipes Multiple custom pipesIt is possible to bundle all frequently used pipes in one Module and import that new module in any component needs the pipes.

Can we create custom pipe in Angular?

Steps Involved In Creating a Custom Pipe In Angular are: 1) Create a Pipe Class and decorate it with the decorator @Pipe. 2) Supply a name property to be used as template code name. 3) Register your Pipe in the module under declarations. 4) Finally, implement PipeTransform and write transformation logic.


1 Answers

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>
like image 170
Bazinga Avatar answered Sep 19 '22 13:09

Bazinga