meli02 meli02 - 5 months ago 49
TypeScript Question

Angular2 Cannot read property 'push' of undefined

Currently, I can make a call to a service and fill a table with records. These records have a selected property, which is toggled by checkboxes for each row. Underneath that table is a button. When I hit this button, I want to loop through the table and create a new array with entries that have selected property == true. I can't seem to initialize the selecterecords array properly.


export class Record {
id: string;
firstname: string;
lastname: string;
salary: string;
selected : boolean;


export class TableComponent implements OnInit {
records: Record[];
selectedrecords: Record[];

private router: Router,
private recordService: RecordService) { }

getRecords(): void {
this.recordService.getRecords().then(records => this.records = records);

ngOnInit(): void {

createselectedRecords() {

for (let rec of this.records) {
if (rec.selected) {




export class RecordService {
getRecords(): Promise<Record[]> {
return Promise.resolve(RECORDS);

getRecord(id: string): Promise<Record> {
return this.getRecords()
.then(records => records.find(record => === id));


By selectedrecords: Record[] you just set this property's type so TypeScript can warn you if you do anything wrong.

To actually initialize the property you can use an empty array right when defining the property:

selectedrecords: Record[] = [];