Home > Software design >  How do I access the id attribute of an option element from the source component?
How do I access the id attribute of an option element from the source component?

Time:12-22

I want to access the id attribute of HTMLOptionElement when a user makes their selection, but it always returns 0 instead of the actual id I passed (such as 1 or 2). the select tag:

<div >
        <select (change)="processSelection($event)" #selectedCategory >
            <option value ="" >Select</option>
            <option [ngValue]="category"  
             *ngFor="let category of categoryNameAndId" [attr.id]="[category.id]">
                {{category.name}}
            </option>
        </select>
    </div>

the source component:

processSelection(event:Event){
   const target  = event.target as HTMLOptionElement;
   const selected = target.value() //works very well
   const id =  target.id //doesn't return desired result
  // const id = Number(target.getAttribute('id'); //doesn't work either
   console.log("id is " id);

  }

But if I implemented something like this <div>{{category.id}}</div> I got the desired result.

CodePudding user response:

You can change to this to get the correct item to get the Id:

const id = this.categoryNameAndId.find(category => category.name === selected)?.id;

Or something like this:

processSelection(event:Event){
   const selectedCategory = this.categoryNameAndId.find(category => category.name === event.target.value);
   const selected = selectedCategory?.name;
   const id = selectedCategory?.id;
}
  • Related