I am grouping some a schoolclass + subject model which then looks like this:

Everything is fine so far, except the selected test type like 'Presentation' is returned as current item as string, but I want the object behind so I can also get the id of that test type!
How can I do that?
With a common select without optgroup I had no problem with that requirement, but with the grouped select it does not work!
Initialization:
let groupedTestTypes = Enumerable.from(responseTestTypes).GroupBy(g => g.schoolclassCode, g =>
g, (key, g) => new TestTypePair(key, Enumerable.from(g).ToArray())).ToArray();
this.testTypes = groupedTestTypes;
HTML
<select class="form-control" [(ngModel)]="currentTestType">
<optgroup *ngFor="let testType of testTypes" label="{{testType.key}}">
<option *ngFor="let item of testType.testTypes">
{{item.name}}
</option>
</optgroup>
</select>
TestType.ts
export default class TestType {
constructor(obj)
{
this.id = obj.id;
this.name = obj.name;
this.schoolclassNumber = obj.schoolclassNumber;
this.subjectName = obj.subjectName
this.schoolclassCode = this.schoolclassNumber + " " + this.subjectName;
}
id: number;
name: string;
schoolclassNumber: string;
subjectName: string;
schoolclassCode: string;
}
TestTypePair.ts
import TestType from './testtype';
export default class TestTypePair {
constructor( public key: string, public testTypes: TestType[]) {
}
}
You can use NgValue directive on your select options:
<select class="form-control" [(ngModel)]="currentTestType">
<optgroup *ngFor="let testType of testTypes" label="{{testType.key}}">
<option *ngFor="let item of testType.testTypes" [ngValue]="item">
{{item.name}}
</option>
</optgroup>
</select>
This is the exact case NgValue directive is meant for - when you have object in displayed as items, you can use it to specify what value to return when you select something. (for example name, id or whole object)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With