Search code examples
angular2-formsangular4-forms

Angular2 How to Handle null value in .find methode


Here i wrote simple .find method its finding my data well but if that record is not available then its displying 1st Record

public _pagedItems : any;
    someval(value){
     if(value.length>=5){
        this._pagedItems= this.allItems.find(e=>e.uniqueid = value);
        this.pagedItems=[];
        this.pagedItems.push(this._pagedItems);

      }

if my uniquId is not avaible then its should display Nodata OR Null


Solution

  • Here is an example for handle null and undefined and return no data like

    Your code is looking wrong. Your are code using (=) symbol. So change (==).

    The difference between = and == (=) equal symbol is assigning value (==) symbol is comparing a value

    For more proper example here,

    public _pagedItems : any[]=[];
        someval(value:string){
    
        if(!this.isObjNull(value) && !this.isObjNull(this.allItems) && this.allItems.length>0){
    
         if(value.length>=5){
              if(this.allItems.find(e=>e.uniqueid ==value)){
                   //you need one data use find
                   this._pagedItems=this.allItems.find(e=>e.uniqueid == value);
    
                  //you need multiple data use filter
                  this._pagedItems = this.allItems.filter(e=>e.uniqueid == value);
              }
             //here Iam logged final variable 
             console.log("Final Paged Items",this._pagedItems);
          }
    }
    }
    
    //here is the method check null and undefined.
    isObjNull(data){
           If(data!=null && data!=undefined){
               return true:
           }else{
                return false;
           }
    }
    

    You can handle html part like this

    <ng-container *ngIf="_pagedItems; else noData">
        <ng-container *ngIf="_pagedItems.length>0; else noData">
            <!--   do you logic here.like *ngFor -->
        </ng-container>
    </ng-container>
    
    <ng-template #noData>
         <p>No data found</p>
    </ng-template>
    

    That's all let try this once. If any error please let me know.

    Note:- here Iam used sample variable please replace your actual variable.

    For comparison related more thing visit here. Difference between == and === in JavaScript