Reputation: 4502
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
Upvotes: 0
Views: 7323
Reputation: 4918
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";
}
Upvotes: 2