[Solved] Cannot read a property push of undefined in angular

Problem

In Angular when pushing items to an Array I get “Uncaught TypeError: Cannot read property ‘push’ of undefined” error as shown below screenshot.

Cannot read a property push of undefined in angular

Code

Here is the code example where this issue occurs, ListEmployeeComponent Component class

Interface IEmployee

Solution

To solve this issue Uncaught TypeError: Cannot read property ‘push’ of undefined, there is a solution given below.

Array Initialization

You have to initialize array using below

or

You can initialize this array in ngOninit() method https://angular.io/guide/lifecycle-hooks, the line is highlighted in below code

Tip: What is Array initialization in TypeScript/JavaScript Mean?

To declare and initialize an array we would use the following syntax

var array_name[:data type]; //declaration
array_name = [value_1,value_2…...value_n] //initialization

Example

var employees: IEmployee[]=[]; //employees array and type is IEmployee
or
var employees=[]; //An array declaration without the data type is to be, of the type any

Add an item to an Array

To add an item to an Array we could use push operations:
var employees=[]
employees.push('Jhon');

Shivaraju M

Over 3+ years experience in IT industry, good knowledge in . Net-based Web applications, windows applications, web services, and SPAs. I have played multiple roles related to technical delivery in multiple domains while working on over 10+ technologies. I am currently focused on continuous improvement and agile project management.

Post a Comment

Previous Post Next Post