4

I need to add custom data attribute to select options. I want it because on change I want to trigger action based on selected attribute (not value)

Here is the code I am using

<select (domChange)="onListUpdate($event)" formControlName="region" id="region" class="selectric form-control">
    <option code="" value="-1">{{ 'select_country' | translate }}</option>
    <option data-isocode="{{region.iso_code}}" value="{{region.id}}" *ngFor="let region of regions">{{region.name['en']}}</option>
</select>

It works when I give static value to data attribute for example, the following works without any problem (notice the data-isocode has static value)

<option data-isocode="abc" value="{{region.id}}" *ngFor="let region of regions">{{region.name['en']}}</option>

However, when I try to use the variable in data-isocode

<option data-isocode="{{region.iso_code}}" value="{{region.id}}" *ngFor="let region of regions">{{region.name['en']}}</option>

It throws me following error

Can't bind to 'isocode' since it isn't a known property of 'option'

How do I pass the data attribute (like in jQuery) with Angular and get the value using FormBuilder?

Ibrahim Azhar Armar
  • 25,288
  • 35
  • 131
  • 207

1 Answers1

7

You can bind to the data- attributes like this:

[attr.data-isocode]="region.iso_code"

You can access the value through an event binding like:

getData(event){
  console.log(event.target.dataset.isocode);
}

Accessing it via this.form.value is not possible though since this.form.value gives the "value" elements only. You have to override the value with your data attribute value onChange if you want to access it there. But it'll be a roundabout way of getting things done.

Rajshri Mohan K S
  • 1,557
  • 17
  • 30