Reputation: 35
Currently, I can make a call to a service and fill a table with records; the records have a selected property, which is toggled by checkboxes for each row.
Underneath that table is a button; when I hit the 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));
}
}
Upvotes: 3
Views: 8701
Reputation: 96899
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:
selectedrecords: Record[] = [];
Upvotes: 4
Reputation: 8992
You need to initialize before using your variable.
constructor(
private router: Router,
private recordService: RecordService) {
this.selectedrecords = new Array<Record>(); // <-- added
}
Upvotes: 0