Why ERROR TypeError: Cannot read properties of undefined (reading 'length')?
Solution 1
The error message
ERROR TypeError: Cannot read properties of undefined (reading 'length')
tells you that, at one point in time, the value of expertList
is undefined
.
So, we can only assume but the probability is high that the value of expertList
is loaded via an asynchronous call. That means as long as the call hasn't returned, the value of expertList
stays undefined.
To get rid of the error you need to adjust the condition in your *ngIf
.
<div id="Expert" *ngIf="expertList?.length > 0">
...
</div>
By adding a ?
the execution of the expression is stopped if a null
or undefined
value occurs, so the error message does not occur anymore. This is called optional chaining.
Solution 2
It can be because expertList
is not available when the component load. Do you fetch that value through HTTP or something?. If so you can do three things.
On your component's constructor, initialize the expertList
variable with an empty array. expertList = []
You can have a variable isLoad
that starts with false
on the constructor and when the fetch end, becomes true
. This variable should be used on the HTML.
<div *ngIf="isLoad">
<i class="fas fa-brain"></i>
<span>Skills: </span>
<div id="Expert" *ngIf="expertList.length > 0">
Expert
<span *ngFor="let skill of expertList">
{{skill.skill}}
</span>
</div>
</div>
Or you can just check that expertList
is not undefined
(with the ?
).
<div id="Expert" *ngIf="expertList?.length > 0">
Expert
<span *ngFor="let skill of expertList">
{{skill.skill}}
</span>
</div>
Related videos on Youtube
doubting
Updated on June 04, 2022Comments
-
doubting almost 2 years
Why the component is rendering correctly but the browser console throws this error?:
ERROR TypeError: Cannot read properties of undefined (reading 'length')
Thank you in advance! :)
member-profile.component.html:
<div *ngIf="member"> <div><img src="..\..\..\assets\images\avatar.png" alt="Avatar" style="width:60px; height: 60px;"><h3>{{ member.name}} {{member.surname}}</h3></div> <div><i class="fas fa-user-tie"></i><span>Role: </span>{{ member.role }}</div> <div><i class="fas fa-at"></i><span>Email: </span>{{ member.email }}</div> <div><i class="fas fa-user-tag"></i><span>Username: </span>{{ member.username }}</div> <div> <i class="fas fa-brain"></i> <span>Skills: </span> <div id="Expert" *ngIf="expertList.length > 0"> Expert <span *ngFor="let skill of expertList"> {{skill.skill}} </span> </div> </div>
-
kvetis over 2 yearsplease include complete code sample
-
D M over 2 yearsPresumably
expertList
isnull
/undefined
. Have you checked that it contains the data you expect?
-