Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get selected object from bound select dropdown with optgroup

Tags:

angular

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

enter image description here

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[]) {
    }
}
like image 520
Pascal Avatar asked Mar 02 '26 01:03

Pascal


1 Answers

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)

like image 200
Stefan Svrkota Avatar answered Mar 04 '26 17:03

Stefan Svrkota



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!