Search code examples
angulartypescriptangular-materialdropdown

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


TLDR: dropdown list is a list of objects. Not sure how to capture multiple attributes of chosen object.

What I currently have working:

I have a simple dropdown list that displays the details of a returned obj through API call:

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

where on my component.ts, I have a testName defined as a string:

testName: string

Through this, i am indeed able to retrieve the correct test.testName based on what user chooses in the dropDown list (based on the specific test clicked by user)

What I need:

I want to extend this further. Lets say I want both test.name and test.results and assign them to variables testName and testResults for use in a further API call. How do i go about doing this?

I've tried changing [value]="test.testName" to [value]="test.testName, test.testResults" and [(ngModel)]="testMap" where testMap is defined in component as: testMap: Map<string, string>.

This unfortunately did nothing and i just end up capturing only test.testName.


Solution

  • You can simply bind your [(ngModel)] variable to be the entire test object. Like this:

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

    I only changed two parts of your code

    (1) The variable binded with [(ngModel)]

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

    You'll need to create a new member variable in your component called testObject which you will be able to use to access any attribute of your selected value.