Obtaining attribute data value upon selection change in Angular 4

Having trouble retrieving the value from data-somedata in my code...

<select class="form-control input-sm" [(ngModel)]="o.id" formControlName="optionals" (change)="menuChange($event)">
  <option *ngFor="let menu_optional of menu_optionals" value="{{ menu_optional.id }}" [attr.data-somedata]="menu_optional.id">{{ menu_optional.name }}</option>
</select>

In my component.ts, I have:

menuChange(event) {
    console.log(event.data);
}

However, the return is undefined. I'm looking to retrieve the value stored in data-somedata attribute.

Answer №1

If the value of attr.data-some-data matches value, you can streamline your code like this:

console.log(event.target.value);

If you specifically need to access the data attribute, then consider using the following snippet:

const selectEl = event.target;

const val = selectEl.options[selectEl.selectedIndex].getAttribute('data-somedata');
// or
const val = selectEl.options[selectEl.selectedIndex].dataset.somedata;

Answer №2

Consider implementing it in this manner:

Instead of using (change), try substituting it with (ngModelChange)

<select class="form-control input-sm" [(ngModel)]="o.id" formControlName="optionals" (ngModelChange)="menuChange($event)">
  <option *ngFor="let menu_optional of menu_optionals" [value]=" menu_optional.id" [attr.data-somedata]="menu_optional.id">{{ menu_optional.name }}</option>
</select>

Answer №3

For those utilizing MatSelect from Angular material version 1 or higher along with Reactive forms, the following solution proved effective for me:

HTML Code:

<mat-form-field class="full-width">
    <mat-select placeholder="Field 1" 
      [formControl]="form.controls['field1']" 
      (change)="dropDownChange($event)">
      <mat-option *ngFor="let fieldOpt of fieldOpts.options" [attr.data-fieldId]="fieldOpts.fieldId" [value]="fieldOpt.id">{{ fieldOpt.name }}</mat-option>
    </mat-select>
</mat-form-field>

Component JavaScript:

dropDownChange(event) {
    let target = event.source.selected._element.nativeElement;
    let selectedData = {
      fieldId: target.getAttribute('data-fieldId'),
      valueId: event.value,
      value: target.innerText.trim()
    };
    console.log(selectedData);
}

If there is a better solution or any flaws in this approach, please do not hesitate to inform me as I am keen on learning more :-)

Answer №4

In Angular material versions above 7

Component.ts

menuChange(event) {
// This method gets the current Host DOM element
console.log(event.option._getHostElement().getAttribute('data-somedata'));
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

ngx-bootstrap encountered an issue: TypeError - _co.openModal is unavailable as a function

Just starting out with ngx-bootstrap, I was attempting to create a modal using the instructions from this site : However, I encountered the following error: ERROR TypeError: _co.openModal is not a function Here are some code snippets: //app.component ...

"Convert a date string to a date object using the verbose moment date

I utilized the materialize datepicker to select a date in French format. Now I need to convert this formatted date back to a date object for use in my API. Here's how I attempted to revert the date to a standard format: moment("dimanche 30 juillet 20 ...

In Typescript, is it correct to say that { [key: string]: any } is identical to { [key: number]: any }?

Recently diving into Typescript has been an interesting journey, especially when stumbling upon weird language behaviors. After writing the following code snippet, I was surprised to see that it compiled and executed successfully: let x: { [key: string]: a ...

Having trouble retrieving information from the API in Angular

Error: There was a Forbidden error (403) when trying to access the URL . xyz.service.ts import { Injectable } from '@angular/core'; import { HttpErrorResponse } from "@angular/common/http"; import {Http, Response} from '@angular/http&ap ...

Refreshing manually will display only the JSON data

Utilizing a NodeJS server to fetch information from a MySQL database and presenting it as a JSON object is the task at hand. app.get('/random', (req, res) => { var connection = mysql.createConnection({ host: 'localhost', ...

Guide to integrating global interfaces into your Nuxt project

Recently diving into the world of Nuxt 3, I've encountered a challenge while exploring TypeScript functionalities. My current goal is to create a versatile NavBar featuring multiple buttons with unique links. To achieve this, I aimed to establish an ...

Retrieving routing information from directives within angular2

const APP_ROUTES: RouterConfig = [ { path: 'app/home', component: HomeComponent, data: { name: 'Home' } } ] Assuming the route configuration is set as displayed above, how can one ...

Issue resolved: Mysterious fix found for background images not displaying in NextJS React components

I am having trouble displaying a background image on an element in NextJs using Typescript and Tailwind. I do not believe it is a TypeScript issue since I am not receiving any errors or IntelliSense warnings. Below is the code I am working with: var classn ...

Issue with res.redirect not properly redirecting to https site

After reading numerous posts with the same title, I have tried several suggestions but none of them have worked. In my Angular2 app with a server API, I am looking to automatically redirect in production if it's not secure. The code below is the fir ...

Angular 2: It is essential to have a distinct instance for Signature Pad

I am seeking assistance with utilizing the signature pad feature in order to capture multiple signatures. Below is a snippet of my code. I have 'n' number of employees and would like each employee to input their signature into the designated box ...

Pressing the confirm button will close the sweet alert dialog

When pressing the confirm button, the swal closes. Is this the intended behavior? If so, how can I incorporate the loading example from the examples? Here is my swal code: <swal #saveSwal title="Are you sure?" text ="Do you want to save changes" cancel ...

Currency symbol display option "narrowSymbol" is not compatible with Next.Js 9.4.4 when using Intl.NumberFormat

I am currently utilizing Next.JS version 9.4.4 When attempting to implement the following code: new Intl.NumberFormat('en-GB', { style: 'currency', currency: currency, useGrouping: true, currencyDisplay: 'narrowSymbol'}); I ...

Steps for exporting various elements from a .vue file

In my Vue project, I am incorporating TypeScript along with Vue. There is a specific scenario where I need to export multiple items from my .vue file. Here's an example of what I want to achieve: // FooBar.vue <template> ... </template& ...

Optimizing the SiteMap.xml for Angular 6: How to Choose the Right Strategy?

I'm looking to add a sitemap.xml file to my project. I already know where it should be placed: "apps": [ { [...] "assets": [ "assets", "favicon.ico", "sitemap.xml", "robots.txt" ], [...] } ] However, I'm unsure about how ...

Utilizing a single route guard for multiple routes with varying authorization requirements

In my Angular 6 project, I currently have an canActivate AuthGuard that is set up to load ComponentA. Now, I am wondering if it's possible to reuse the same AuthGuard for Component B, even though the authorization logic for Component B is completely ...

Is there a way to efficiently load the json files only upon clicking the corresponding language button?

Currently, I am using a tutorial on implementing translations in Angular2. The implementation works well, but I would like to optimize it by loading json files only when the associated language button is clicked. Can someone assist me with this? // app/tr ...

Encountering a value accessor error when attempting to test a simple form in Angular 4 and Ionic 3

My ionic form is quite simple: <ion-header> <ion-navbar> <ion-title>Foo</ion-title> </ion-navbar> </ion-header> <ion-content padding> <form [formGroup]="fooForm"> <ion-item> ...

`Angular2 - exploring the complexities of function scope`

I'm facing a challenge while working on my Angular2 Sample with the http module. Here is a snippet from my component: app.loginComponent = ng.core.Component({ selector: 'login', templateUrl: 'app/login/login.html&ap ...

Set up Angular library by downloading from a specified local or network location

If I were to create an Angular library using the following commands: ng new libraries-workspace --create-application=false cd libraries-workspace ng generate library test-library After creating and building the library using the command below: ng build te ...

Tips for ensuring session token verification remains intact upon reloading

I am currently in the process of developing a website using the Next.js framework and I am seeking advice on how to prevent the reload effect that occurs when transitioning from the login page back to the main page for just a fraction of a second. Below i ...