Cannot Read Properties of Undefined is a runtime Error.
This error occurs when you try to access a property or method of a variable that is currently undefined.
This error means that when your code is trying to access one of its properties of a variable or object that has not been initialized.
Example: Suppose you are accessing the name property from a user object, but the user object is undefined, then Angular throws an error Cannot Read Properties of Undefined.
user.name
Common Causes in Angular
1. Data Not Loaded (Async Issue)
This is the most common issue
in typescript file
user!: any;
ngOnInit() {
this.http.get('api/user').subscribe(res => {
this.user = res;
});
}
in template file
{{ user.name }}
Before the API response arrives, the user is undefined.
2. Incorrect API Response Structure
Suppose you have an API response
{ "data": { "name": "John" } }
But you are accessing in the frontend
user.name
But it should be
user.data.name
3. Variable Never Initialized
You declared, but never assigned any value.
let product;
console.log(product);
4. ngFor Loop on Undefined Array
When items are an undefined array.
<div *ngFor="let item of items">
Best Solutions and Fixes
✅ 1. Use Safe Navigation Operator (?.)
Angular will only access the name if the user exists.
{{ user?.name }}
✅ 2. Use *ngIf
Render template only when data is available.
<div *ngIf="user">
{{ user.name }}
</div>
✅ 3. Initialize Variable
let product: any = "";
console.log(product);
✅ 4. Initialize Array Variable
let items: any[] = [];
console.log(items);