如何在Angular中通过mat-options(下拉列表)提取用户选择的对象的多个属性?

How to extract multiple attributes of a object chosen by user through mat-options (drop down list) in Angular?

TLDR:下拉列表是一个对象列表。不确定如何捕获所选对象的多个属性。

我目前的工作:

我有一个简单的下拉列表,显示通过 API 调用返回的对象的详细信息:

 <mat-form-field class="testSection">
        <mat-label>Available Test Results:</mat-label>
        <mat-select [(ngModel)]="testName" name="testName" ngDefaultControl>
          <mat-option *ngFor="let test of tests" [value]="test.testName">
            {{ test.testName + test.testType + test.results + test.cohortId}}
          </mat-option>
        </mat-select>
 </mat-form-field>

在我的 component.ts 上,我有一个定义为字符串的 testName:

testName: string

通过这个,我确实能够根据用户在下拉列表中选择的内容(根据用户点击的特定test)检索到正确的test.testName

我需要的:

我想进一步扩展。 假设我想要 test.nametest.results 并分配它们添加到变量 testNametestResults 中,以便在进一步的 API 调用中使用。我该怎么做呢?

我试过将 [value]="test.testName" 更改为 [value]="test.testName, test.testResults"[(ngModel)]="testMap" 其中 testMap 在组件中定义为:testMap: Map<string, string>.

不幸的是,这什么也没做,我最终只捕获了 test.testName。

您可以简单地将您的 [(ngModel)] 变量绑定为整个测试对象。像这样:

 <mat-form-field class="testSection">
        <mat-label>Available Test Results:</mat-label>
        <mat-select [(ngModel)]="testObject" name="testName" ngDefaultControl>
          <mat-option *ngFor="let test of tests" [value]="test">
            {{ test.testName + test.testType + test.results + test.cohortId}}
          </mat-option>
        </mat-select>
 </mat-form-field>

我只更改了你代码的两部分

(1) [(ngModel)]绑定的变量

(2) [value]="test.testName"[value]="test"

您需要在名为 testObject 的组件中创建一个新的成员变量,您可以使用它来访问所选值的任何属性。