user17260293
user17260293

Reputation: 85

How to get id of value from select?

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 class="form-select w-50 p-2 text-primary mt-2" 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)
  }

Upvotes: 0

Views: 1372

Answers (2)

Kanishk Anand
Kanishk Anand

Reputation: 1702

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

Upvotes: 0

Devang Patel
Devang Patel

Reputation: 1843

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 class="form-select w-50 p-2 text-primary mt-2" aria-label="select" (change)="onChangeObj($event.target.value)">
    <option *ngFor="let category of (categories$ | async)" [value]="category.id">{{category.categoryName}}</option>
</select>

Upvotes: 1

Related Questions