3

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));
    }
}

2 Answers 2

4

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[] = [];
Sign up to request clarification or add additional context in comments.

Comments

0

You need to initialize before using your variable.

constructor(
 private router: Router,
 private recordService: RecordService) { 
 this.selectedrecords = new Array<Record>(); // <-- added 
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.