ERROR TypeError: Cannot read property ‘sort’ of undefined

When you get ERROR TypeError: Cannot read property ‘sort’ of undefined while running angular app, the main cause of this error would be array initialization in the ‘app.component.ts” file.

Solution:

Open ‘app.component.ts’ file in your favorite editor and check whether the component property (array) used to list multiple items is initialized either while declaring or in the constructor.

export class AppComponent {

  items: Item[] = []; // <-- component property
  
  constructor() {
	//this.items= [
	//	new Item('Scooter', 45,000),
	//	new Item('Car', 2,50,000),	
	//];
  }
  
  addItem(vehicle: HTMLInputElement, price: HTMLInputElement): boolean {
	
	this.items.push(new Item(vehicle.value, price.value,0));
	vehicle.value ='';
	price.value ='';
	return false;
  }
  
  //sorting items based on price
  sortedItems(): Item[] {   
	return this.items.sort((a: Item, b: Item) => b.price- a.price);
  }

Note, try to initialize while declaring as shown below

items: Item[] = []; // <-- Array initialization (Item is a component)

(or)

Initialize items via constructor

constructor() {
	this.items= [
		new Item('Scooter', 45,000),
		new Item('Car', 2,50,000),	
	];
  }

Once you make changes to your code as mentioned above, then try running your application. Hope this solves your issue.

Further Learning

References

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments