简体   繁体   中英

How to handle undefined object property in angular 5

I tried to fix the undefined error by setting the object property value to an empty string but its still giving the error as mentioned below:

ERROR TypeError: Cannot read property 'notes' of undefined

TS

let notes;
if (typeof manufacturer_field.manufacturer_guidelines[0].notes == undefined){
  notes = '';
} else {
  notes = manufacturer_field.manufacturer_guidelines[0].notes;
}

HTML

<p *ngIf="field.notes?.length">{{field.notes}}</p>

I referred this answer but that didn't work: How to handle 'undefined' in javascript

If notes array element 0 is undefined, then this will throw an error:

if (typeof manufacturer_field.manufacturer_guidelines[0].notes == undefined){

because you are checking if the property is undefined, when what is actually undefined is the .manufacturer_guidelines[0] item.

instead, you can do:

if (!manufacturer_field.manufacturer_guidelines[0]){
     manufacturer_field.manufacturer_guidelines[0] = (assign it whatever value belong to this sort of item, and then once you know it is valid, then add notes)
}

Also, you are assigning the string to "notes" variable, not the actual array item.

So lets say i had a cars array:

if (!cars[0]) {
   cars[0] = <Car>{};
   cars[0].color = "blue";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM