Search code examples
angularangular5angular2-template

How to handle null variable while dealing with two way data binding in Angular 2+


I am using same component for edit as well as add new entries.

if(this.action='edit'){
    this._PersonnelService.getUsersById(this.selectedperid)
      .subscribe((userdata: Iuser) => { this.personnel = userdata[0]; this.personnel.perid = this.selectedperid;console.log(userdata[0]); }, (error) => {
        this.statusMessage = 'Problem with service. Please try again.'
        console.error(error);
      });
   }
    else{     this.personnel=null}

  }

Which means that if the this.action variable is add this.personnel will be set to null.

Now in HTML I have elements such as :

<input type="text"   class="form-control" name="PerFullName"  
[(ngModel)]="personnel.perfullname" id="fullname ">

I am getting truck load of errors in console. My textboxes aren't visible.
How do I fix this?


Solution

  • Use the elvis operator ? in your html

    <input type="text"   class="form-control" name="PerFullName"  
    [ngModel]="personnel?.perfullname" (ngModelChange)="personnel?.perfullname personnel?.perfullname = $event : null" id="fullname ">
    

    and the ?? in your javascript to set defaults incase of null

    const j = null
    y = j ?? 'Anonymous'
    

    And this was answered previously here two-way-binding-with-elvis-operator.