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

1
  • The problem isn't about notes. It's about field and/or manufacturer_field.manufacturer_guidelines[0]. Commented May 16, 2018 at 13:50

1 Answer 1

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";
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.