0

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

Rahul Dagli
  • 4,301
  • 15
  • 47
  • 85
  • The problem isn't about `notes`. It's about `field` and/or `manufacturer_field.manufacturer_guidelines[0]`. – Joseph May 16 '18 at 13:50

1 Answers1

2

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";
}
David Anthony Acosta
  • 4,766
  • 1
  • 19
  • 19