Search code examples
htmlangulartypescriptcollectionsdata-binding

Angular - HTML - pass selected value from drop down to TS method on button click


The issue I'm having is that I'm unable to access the .value and .id in {{selectItem}} to send them back to the typescript for a HTTP post later on. While there is no actual error I have exceptions and have googled to resolve yet to no avail.

Exception thrown: 'System.IO.IOException' in System.Net.Sockets.dll Exception thrown: 'System.IO.IOException' in System.Private.CoreLib.dll Exception thrown: 'System.Threading.Tasks.TaskCanceledException' in System.Net.Http.dll Exception thrown: 'System.Threading.Tasks.TaskCanceledException' in System.Private.CoreLib.dll Exception thrown: 'System.Threading.Tasks.TaskCanceledException' in System.Private.CoreLib.dll

I understand that {{selectedItem | json}} just places the selected item into JSON form but I want to simply pass the .id and .values back to a method on a button click. Struggling for about a week. Any guidance appreciated.

<div div class="main-search-user-name">
        <mat-form-field>
          <mat-label>Search Select User</mat-label>
          <mat-select [(ngModel)]="selectedItem">
            <mat-option *ngFor="let getddusers of getusers" [id]="getddusers.id" [value]="getddusers.value">
              {{getddusers.id}} {{getddusers.value}}
            </mat-option>
          </mat-select>
        </mat-form-field>
        {{selectedItem | json}}
        <button type="button" class="btn btn-primary btn-sm">Search</button>
        <button type="button" class="btn btn-primary btn-sm" (click)="displayName('{{getddusers.id}}' + '{{getddusers.value}}')">Search</button>
</div>

Solution

  • You would need to change the property binding from [value]="getddusers.value" to [value]="getddusers".

    Doing so will ensure that selectedItem represents the entire object, and you can then simply use this.selectedItem.id and this.selectedItem.value within displayName() in your Component ts file.