Search code examples
javascriptangulartypescriptangular4-forms

ERROR TypeError: Cannot read property 'clientId' of null


After clicking on my object I change the component to another to update this object. in this component for update I have a form that contains a select element with options which should be initialized with values from database (in method OnInit)

and I need to select by default from this list of values the value of my object

 <label>Catégorie Client:</label>
 <select class="form-control" [(ngModel)]="client.clientId" >
     <option></option>
     <option *ngFor="let client of clients" [value]="client.clientId">{{client.name}}</option>
 </select>

The problem is that the client can be null and I want in this case to show <option></option> as default value with empty value, but I got error

cannot read null value

I have my object instantiated ...

Thanks for helping.


Solution

  • [(ngModel)]="client.clientId" generates the error. client is not available here, you declared it in your optiontags

    Be aware [value]="xxx" supports string only, if your clientId is number, you'd better choose [ngValue]="xxx"

     <label>Catégorie Client:</label>
     <select 
       class="form-control" 
       [(ngModel)]="selectedClient" >
       <option></option>
       <option 
         *ngFor="let client of clients" 
         [ngValue]="client"
       >
       {{client.name}}
       </option>
     </select>
    

    selectedClient needs to be initialized by one item of clients,

    as ConnorsFan mentioned, you can leave selectedClient as null, so nothing would be selected at the beginning.