Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - add custom (data) attribute to <option> using ngFor

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?

like image 385
Ibrahim Azhar Armar Avatar asked Nov 15 '25 11:11

Ibrahim Azhar Armar


1 Answers

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.

like image 161
Rajshri Mohan K S Avatar answered Nov 17 '25 01:11

Rajshri Mohan K S



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!