meli02 meli02 - 1 month ago 11
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.

Record.ts

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


table-component.ts

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


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

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

ngOnInit(): void {
this.getRecords();
}


createselectedRecords() {

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

}
console.log(this.selectedrecords);
}

}
}


record-service.ts

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

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

Answer

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[] = [];