How can we retrieve the target element for an 'onSelectionChange' DOM event in Angular 6?

When using Angular 6, I want to retrieve the "formControlName" of the corresponding element whenever the selection changes.

HTML

    <mat-form-field *ngIf="dispatchAdviceChildForAdd._isEditMode" class="mat-form-field-fluid">
        <mat-select placeholder="Select Product" formControlName="newProductCode" required>
            <mat-option *ngFor="let pl of productList" value="{{pl.productCode}}" (onSelectionChange)="changeValues($event,pl)">{{pl.productCode}}</mat-option>
        </mat-select>
        <mat-hint align="start">
            <strong>Select</strong>
        </mat-hint>
    </mat-form-field>

TYPESCRIPT "changeValues"

 changeValues(event, data: ProductListModel) {
      // need to access formControlName here
 }

I have attempted various methods but haven't had success:

 changed(event) {
   console.log(event.target.id); 
 }

I have also experimented with:

changed(event) {
 const target = event.target || event.srcElement || event.currentTarget;
 const idAttr = target.attributes.id;
 const value = idAttr.nodeValue;
}

Answer №1

Is there something I'm overlooking, why not simply do it like this:

changeValues(event, data: ProductListModel, controlName: string) {
      // here I need formControlName
 }
<mat-form-field *ngIf="dispatchAdviceChildForAdd._isEditMode" class="mat-form-field-fluid">
    <mat-select placeholder="Select Product" formControlName="newProductCode" required>
        <mat-option *ngFor="let pl of productList" value="{{pl.productCode}}" (onSelectionChange)="changeValues($event,pl,'newProductCode')">{{pl.productCode}}</mat-option>
    </mat-select>
    <mat-hint align="start">
        <strong>Select</strong>
    </mat-hint>
</mat-form-field>

To access the component itself, you can use:

changeValues(event, something, matComponent) {
  // not using material components so I don't know the class

}
<mat-form-field *ngIf="dispatchAdviceChildForAdd._isEditMode" class="mat-form-field-fluid">
    <mat-select #matSelect placeholder="Select Product" formControlName="newProductCode" required>
        <mat-option *ngFor="let pl of productList" value="{{pl.productCode}}" (onSelectionChange)="changeValues($event,pl, matSelect)">{{pl.productCode}}</mat-option>
    </mat-select>
    <mat-hint align="start">
        <strong>Select</strong>
    </mat-hint>
</mat-form-field>

This example uses template referencing with #matSelect and then passing it to the callback function.

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

What are the steps to convert this code into Angular syntax?

After realizing that using jQuery alongside Angular is not a good practice, I am determined to modify my code in this Angular App to eliminate the need for jQuery. Currently, I have a page that displays menu items fetched from the server and I loop throug ...

Is there a way to access the value or key of a JSON property in an Angular template for rendering purposes?

Having trouble displaying the JSON values of certain properties on screen. Utilizing Angular Material table to showcase my JSON response. The code snippet below is responsible for rendering the JSON data: <mat-card-content class="dashboard-card-cont ...

Guide on accessing js file in an Angular application

I have a component where I need to create a function that can search for a specific string value in the provided JavaScript file. How can I achieve this? The file path is '../../../assets/beacons.js' (relative to my component) and it's named ...

Encountering an error with loading %5Bobject%20Object%5D on a webpack-generated JavaScript file hosted in an express server because of Stylus styles

I have been experimenting with enhancing the example linked here. Initially, everything worked smoothly when I used npm start. However, I wanted to integrate it into an existing ExpressJS project. To achieve this quickly, I copied the three js files to the ...

The Subscribe function in Angular's Auth Guard allows for dynamic authorization

Is there a way to check if a user has access by making an API call within an authentication guard in Angular? I'm not sure how to handle the asynchronous nature of the call and return a value based on its result. The goal is to retrieve the user ID, ...

Angular2: Going back a couple of steps

Is there a method to go back two steps when clicking on (click) goBack($event) instead of using just this.location.back()? I am looking for a way to access a list of locations in an array and cut out the last element. ...

Getting the most out of TypeScript Enum in Angular 6

I have a situation where I am storing the numeric value of an enum in my database and then displaying it in another part of the UI. Now, I need to retrieve the string value linked with that numeric value from the enum in a separate Angular component. Here ...

Validating React components with TypeScript using an array structure where the field name serves as the key

Trying to implement form validation with React. I have a main Controller that contains the model and manages the validation process. The model is passed down to child controllers along with the validation errors. I am looking for a way to create an array ...

Obtain the specific key and its corresponding value using Angular

I am seeking assistance on how to extract a specific key and its value from an object. {RuleExpression: 'DEFAULTS.epHDefaults.gen== true', Action: Array(0), DefaultActions: Array(3)} Action: [] DefaultActions: (3) [{…}, {…}, {…} ...

"Unlocking the treasure trove: Extracting a single item from my Firebase real-time database using

Searching for the user's article in my Realtime database to display information. This is my Ionic script page Below are the imports I have: I am able to retrieve the user's ID, but I'm facing difficulty in fetching this real-time data fro ...

Hello everyone, can someone provide guidance on integrating Spring Boot session with an Angular project?

Can anyone provide guidance on utilizing a Spring Boot session in an Angular project? I am looking to send the login and password via POST request in the following image Click here for image description ...

Using Angular's asyncValidator in conjunction with BehaviorSubject allows for real

Currently, I am working on developing an Angular form. Below is a snippet of my code where I am attempting to construct a multi-group form with an async validator. The scenario involves validating whether a number exists in a specific list. In a real-worl ...

What is the best way to restrict a mapped type in typescript to only allow string keys?

In the Typescript documentation, I learned about creating a mapped type to restrict keys to those of a specific type: type OptionsFlags<Type> = { [K in keyof Type]: boolean; }; If I want to use a generic type that only accepts strings as values: t ...

Dynamic routing with ngIf in Angular 2's router system

Is there a way to use *ngIf with dynamic router in Angular? Let's say I have a top navigation component with a back button, and I only want the back button to be visible on the route 'item/:id'. I tried using *ngIf="router.url == '/ite ...

An error is encountered when attempting to retrieve the list using axios

For this project, I am required to fetch a list from the following resource: http://jsonplaceholder.typicode.com/photos The controller setup is as follows: @JsonController('/photo') @Service() export class PhotoController { const ...

`Angular2 Reactively-shaped Form Elements with BehaviorSubject`

As a newcomer to Angular, I am struggling with updating reactive forms after making asynchronous calls. My specific challenge involves having a reactive form linked to an object model. Whenever there is a change in the form, it triggers an HTTP request th ...

Guide to implementing scheduled tasks in a Node.js API using Express

Currently, my Node API has multiple endpoints, and while they work well for the most part, there is one endpoint that struggles with processing large requests taking up to 1 hour. To handle this, I am considering implementing a system where instead of wait ...

In what way can a piped operator in rxjs be influenced by the value returned by a subsequent operator?

When attempting to examine values between operators in an rxjs pipe, I decided to use tap to log them to the console. I added two taps, one before a map operator used for sorting an Array, and one after. Surprisingly, both taps logged the same sorted Arra ...

The TypeScript error message indicates that a value typed as 'string | undefined' cannot be assigned to a type 'string'

In my TypeScript-based React application where I am utilizing material-ui for components, I am currently working on creating a wrapper for material-ui's input. Here is the code snippet: import FormControl, { FormControlProps } from "@material-ui/core ...

Anticipate the absence of a specific object length

I have an Object that I need to test for null: getLastTeamUpdatedItemLogBuffer(): IBufferElement { const storageItems = this.storageSvc.getItem(StorageKey.lastTeamUpdatedItem, true) as IBufferElement; return storageItems || null; } This is the IBufferE ...