Home > Software engineering >  Typescript property returning undefined
Typescript property returning undefined

Time:12-02

I have encountered very weird behavior using angular model when user selects from an option. I will provide screenshots code snippets. In summary, I am getting undefined for property that is populated. Model object returns expected string but if I directly call the property, it returns undefined.

Object that contains all properties, followed by direct call:

enter image description here

enter image description here

<ng-template>
   <label >Source Name :</label>
   <div >
      <select [(ngModel)]="opcoReference.opcoRef.tntSourceName" >
         <option *ngFor="let object of opcoReference.origSourceName" [ngValue]="object.code">{{object.desc}}</option>
      </select>
   </div>
</ng-template>

CodePudding user response:

From your screen I don't see that opcoReference.origSourceName exists.

But if this is not the case then probably data is not ready when it is rendering. Try to use this

<ng-template>
   <label >Source Name :</label>
   <div  *ngIf="opcoReference">
      <select [(ngModel)]="opcoReference.opcoRef?.tntSourceName" >
         <option *ngFor="let object of opcoReference.origSourceName" [ngValue]="object.code">{{object.desc}}</option>
      </select>
   </div>
</ng-template>

CodePudding user response:

To answer your actual question, what is happening is tntSourceName is undefined at the time of the console log and then set later.

The reason it's confusing is because your first console.log() is passed a reference to the object, and the value in the console changes as the object changes. If you want to see the value at that instant try using JSON stringify then JSON parse, and you will see tntSourceName is undefined at the time of the log.

Edit: either of the other two answer should help you prevent errors in your code resulting from tntSourceName being undefined.

CodePudding user response:

This is just from the browser console lazy loading the object properties. ie. they are not loaded until you expand the object in the debugger. Perhaps you want to wait for tntSourceName to be populated before rendering the select?

<div  *ngIf="opcoReference.opcoRef.tntSourceName">
      <select [(ngModel)]="opcoReference.opcoRef.tntSourceName" >
         <option *ngFor="let object of opcoReference.origSourceName" [ngValue]="object.code">{{object.desc}}</option>
      </select>
</div>
  • Related