Home > Blockchain >  How to get id of value from select?
How to get id of value from select?

Time:12-31

I'm trying to get id from the list, but in response I get an object like this:

Event {isTrusted: true, type: "change", target: select.form-select.w-50.p-2.text-primary.mt-2, currentTarget: select.form-select.w-50.p-2.text-primary.mt-2, eventPhase: 2, …}

html:

<select  aria-label="select" (change)="onChangeObj($event)">
    <option *ngFor="let category of (categories$ | async)" [value]="category.id">{{category.categoryName}}</option>
</select>

ts:

  selectedObj= '';

  onChangeObj(newObj: any) {
    this.selectedObj = newObj;
    console.log(this.selectedObj)
  }

CodePudding user response:

I would suggest to use two way data binding but If you don't want to use that then you need to get it from $event.target.value

<select  aria-label="select" (change)="onChangeObj($event.target.value)">
    <option *ngFor="let category of (categories$ | async)" [value]="category.id">{{category.categoryName}}</option>
</select>

CodePudding user response:

What you're getting is an Event object. You need to extract the value from this object using event.target.value.

TS:

 selectedObj= '';

  onChangeObj(event: Event) {
    this.selectedObj = (event.target as HTMLSelectElement).value;
    console.log(this.selectedObj)
  }

More details : https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event

  • Related