Search code examples
angular2-templateangular2-filtering

Angular2 Search Filter How to display No Record is found


<input Type="text" (keyup)="someval('$event.target.value')"/>    
<table>
    <tr>
    <th> Id</th>
    <th>Name</th></tr>
    <tr *ngFor="let emp of pagedItems">
    <td>{{emp.Id}}</td>
    <td>{{emp.Name}}</td>
    </tr>
     <tr *ngIf="ErrorHandle">
                            <td colspan="5">
                               {{ErrorMsg}}
                            </td>
                        </tr>

Typescript

Here i writen some code to handle my Search text box its accepect Id value and find rec within the table.When Record is their its display the Rec but wen its not available i wana 2 hide *ngFor

someval(value){
  if(value.length>=5){
   this._pagedItems= this.allItems.find(e=>e.uniqueid == value);
    if(this._pagedItems == undefined){
      this.ErrorHandle=true;
      this.ErrorMsg="No Such Record is Present......."
    }
    else{

      this.pagedItems=[];
      this.pagedItems.push(this._pagedItems);
    }

Solution

  • You can do something like following code. I create it in FIDDLE

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
      name = 'Angular 6';
      ErrorHandle :Boolean = false;
      ErrorMsg :string ="No Such Record is Present.......";
      allItems = [{ Id: 1, Name: "chintan" }]
      pagedItems = [];
      emp = { Id: 1, Name: "chintan" };
    
      someval(value) {
        if (value) {
          this.pagedItems = [];
          let emp = this.allItems.find(e => e.Id == value);
          if (emp == undefined) {
            this.ErrorHandle = true; 
          } else {
            this.ErrorHandle = false;
            this.pagedItems.push(emp);
          }
        }
      }
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/2.0.0-beta.17/angular2-all-testing.umd.dev.js"></script>
    <hello name="{{ name }}"></hello>
    <p>
    	Start editing to see some magic happen :)
    </p>
    
    
    <input Type="text" (keyup)="someval($event.target.value)" />
    <table>
    	<tr *ngIf="!ErrorHandle">
    		<th> Id</th>
    		<th>Name</th>
    	</tr>
    	<tr *ngFor="let emp of pagedItems">
    		<td>{{emp.Id}}</td>
    		<td>{{emp.Name}}</td>
    	</tr>
    	<tr *ngIf="ErrorHandle">
    		<td colspan="5">
    			{{ErrorMsg}}
    		</td>
    	</tr>
    </table>