Angular 使用optgroup从绑定选择下拉列表中获取选定对象

Angular 使用optgroup从绑定选择下拉列表中获取选定对象,angular,Angular,我将一些学生分组为一个班级+科目模型,该模型如下所示: 到目前为止,一切都很好,除了像“Presentation”这样的选定测试类型作为当前项作为字符串返回外,但是我希望后面有对象,这样我也可以获得该测试类型的id 我该怎么做 使用公共选择而不使用optgroup时,我对该要求没有问题,但使用分组选择时,它不起作用 初始化: let groupedTestTypes = Enumerable.from(responseTestTypes).GroupBy(g => g.schoolcl

我将一些学生分组为一个班级+科目模型,该模型如下所示:

到目前为止,一切都很好,除了像“Presentation”这样的选定测试类型作为当前项作为字符串返回外,但是我希望后面有对象,这样我也可以获得该测试类型的id

我该怎么做

使用公共选择而不使用optgroup时,我对该要求没有问题,但使用分组选择时,它不起作用

初始化

 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>
TestTypePair.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;
}
import TestType from './testtype';
export default class TestTypePair {
    constructor( public key: string, public testTypes: TestType[]) {
    }
}

您可以在选择选项时使用
NgValue
指令:

<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>

{{item.name}

这正是
NgValue
指令的目的-当您将对象显示为项目时,您可以使用它指定在选择某项时返回的值。(例如名称、id或整个对象)

darn。。。我只是比较了一下我的普通选择,是的,我忘记了顺便说一句,[ngValue]=“item”,而不是[ngValue]=“testType”;-)谢谢你@帕斯卡:是的,这是
,我的错。:-)别担心,像这样的小错误总是发生在每个人身上。:-)嘿,没什么大不了的,这也发生在我身上;-)