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

Time:01-05

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 >
        <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" >Search</button>
        <button type="button"  (click)="displayName('{{getddusers.id}}'   '{{getddusers.value}}')">Search</button>
</div>

CodePudding user response:

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.

CodePudding user response:

You can use selectedItem variable in component's displayName() method. Since you are using selectedItem in ngModel, It'll be updated in component i.e

//app.component.ts

export class AppComponent {
  selectedItem: any= null;
  
  displayName(){
     //you can use selectedItem here
    console.log("Selected user"  this.selectedItem.id);
  }

}
  •  Tags:  
  • Related