Using Angular: How to set the index value from a dropdown to a local variable after a button is clicked

Can someone please provide guidance on how to assign the index value (i = index) to EmployeeIndex: any; after a button click event?

Your suggestions are greatly appreciated.

Here is my code:

HTML

<select class="form-control"  [(ngModel)]="EmployeeName">
    <option *ngFor="let employeeItem of getEmployeeeList(); let i = index" [value]="i">
        {{employeeItem.EmployeeName}}
    </option>
</select>

<button (click)="updateBook()" *ngIf="dep.No!=0" class="btn btn-primary">
    Update
</button>

TS

EmployeeIndex : any;

updateBook() {
    this.EmployeeId = this.employeeFiltered[this.EmployeeIndex].EmployeeId;
    
    var val = {
      No:this.No,
      EmployerName:this.EmployerName,
      EmployeeName:this.EmployeeName,
      Project:this.Project,
      Date:this.Date,
      Spent:this.Spent,
      VAT:this.VAT,
      Total:this.Total,
      Comment:this.Comment};

      this.service.updateBook(val).subscribe(res=>{
          alert(res.toString());
      });
}

Answer №1

This particular method is functioning properly, utilizing the (change) event. However, I am in urgent need of a solution that involves using the (click) event instead.

HTML

<select class="form-control"  [(ngModel)]="EmployeeName" (change)="onChangeEmployee($event)">
                <option *ngFor="let employeeItem of getEmployeeeList(); let i = index" [value]="i">
                       {{employeeItem.EmployeeName}}
                </option>
            </select>

TS

onChangeEmployee(event: any)
{
  console.log("EmployeeIndex " + this.employeeFiltered[event.target.value].EmployeeId); // 0
}

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

Issue with Angular 9 application: Unable to properly render form fields within a Material Design Dialog

I'm currently developing a "Tasks" application using Angular 9 and PHP. I've encountered an error that says Cannot find control with name: <control name> when attempting to pre-fill the update form with data. Here is the form template: &l ...

``I'm facing an issue with Ionic 4's npm run build --prod command not functioning properly when deploying

Embarking on my first project with Ionic 4, I have previously worked with Ionic 3 where I used to build for the web using the command: npm run build --prod However, when attempting to build the Ionic 4 project with the same command, it generates an exces ...

Changing the name of an Angular2 import module

Deciding to improve readability, I opted to rename the @angular module to angular2 and gain a better understanding of how imports function. Prior to making this change, the systemjs.config.js appeared like so: (function(global) { var map = { ...

ReactJs Error: Unable to access property value because it is undefined (trying to read '0')

I am currently attempting to retrieve and display the key-value pairs in payload from my JSON data. If the key exists in the array countTargetOptions, I want to show it in a component. However, I am encountering an error message stating Uncaught TypeError ...

Having issues with JSON.stringify not properly handling every property within an object in Typescript

While using JSON.stringify in Typescript, I encountered an issue where not all properties of the outermost object were being stringified. Here is the code snippet that showcases the problem: class Criterion { '@CLASS' = 'xyz.abc.Criterio ...

Removing an item from an array depending on a specific condition and index

I am working with an array structure that looks like this: [ {key: 4, data: {…}, qText: {…}}, {key: 4, data: {…}, qText: {…}, isVisible: false}, {key: 5, data: {…}, qText: {…}, isVisible: false}, {key: 4, data: {…}, qText: {…}, isVi ...

I am looking to enhance my array of objects by implementing a filter. It is important that the filter does not allow for duplicate checkboxes with the

My website : On the left-hand side of my webpage, there is a set of checkboxes with some repeated names that I don't want. For example, "Rice" is repeated twice but I only want it to display once. When checking the Rice checkbox, it should show all c ...

During the installation of Angular CLI, an error occurred indicating an unexpected ending of JSON input while parsing near the string '...gsJjnNLbV xrOnxOWiCk'

C:\Users\BB>node --version v14.15.0 C:\Users\BB>npm --version 8.3.2 npm install -g @react/react-native npm ERR! Error: Unable to find module '@react/react-native' npm ERR! A detailed log of this process can be locate ...

What could be the reason for the authentication issues in ionic/angular?

An authentication application has been created to receive user information and tokens (jwt) from the server. The data is stored locally and used for further computations within the app. For route guarding, if the token is available, it should proceed to th ...

Typescript classes fail to adhere to interface types

interface IFoo { method: (ha: string) => void; } class Foo implements IFoo { public method(ha) {} } The message displayed when hovering over the 'ha' parameter in the class method reads: Parameter 'ha' implicitly has an &apo ...

Eliminate the "Potential 'undefined' Object" error without resorting to non-null assertion or optional chaining

Below is the code snippet I am working with: export type ConditionalItemType = [ { condition: string }, { [key: string]: FormItemDataType } ]; export type ConditionalItemDataType = ConditionalItemType[]; export type FormItemDataType = { required: bo ...

Having trouble showing the fa-folders icon in Vuetify?

Utilizing both Vuetify and font-awesome icons has been a successful combination for my project. However, I am facing an issue where the 'fa-folders' icon is not displaying as expected: In the .ts file: import { library } from '@fortawesome/ ...

The error message "Cannot send headers after they have already been sent to the client" is caused by attempting to set headers multiple

Although I'm not a backend developer, I do have experience with express and NodeJS. However, my current project involving MongoDB has hit a roadblock that I can't seem to resolve. Despite researching similar questions and answers, none of the sol ...

Error message during ng Build Prod: Component declared in two modules when it should be in the same module

When running the ng build --prod command, I encountered an error message that is causing some confusion: The error states: Type SiteSecurity in "PATH"/siteSecurity.component.ts belongs to the declarations of 2 modules: SiteSecurityModule in "PATH"/s ...

Ways to incorporate a notification feature with an icon or image

I'm looking to create a visually dynamic icon/image similar to mobile device notifications, but primarily for desktop use. This image will be positioned before some text. For instance: https://i.sstatic.net/MHocy.pngSome Text This design features tw ...

Stream in Node.js seems to have frozen

I am looking to develop a basic csv parser using the csv module and effectively handle errors when the file is missing. If I remove the sleep functions, the code successfully reaches the Finally statement (and produces an error output). What am I overloo ...

Reacting to the surprise of TS/JS async function behaving differently than anticipated

It appears that I'm facing a challenge with the small method; not sure if my brain is refusing to cooperate or what's going on. async fetchContacts() { await this.http.get('http://localhost:3000/contacts') .subscribe(res =& ...

Passing an event from onSubmit in React without using lambdas

Within our current project, the tslint rule jsx-no-lambda is in place. When attempting to capture event from onSubmit, this is how I typically write my code: public handleLogin = (event: React.FormEvent<HTMLFormElement>) => { event.preventDe ...

What steps can I take to ensure that a function is only executed after at least two Observables have returned data?

I am currently working on an Angular Reactive form that incorporates custom components. The form includes basic Form Fields and a Froala editor, customized with dropdowns that fetch values from the backend using observables. This is where I encounter some ...

An error was encountered at line 7800, character 18 in the three-core.d.ts file in the node_modules/@types/three directory. The error message reads: "Cannot find name 'VRDisplay

I encountered an error in my Angular 6 app while running ng serve ERROR in node_modules/@types/three/three-core.d.ts(7800,18): error TS2304: Cannot find name 'VRDisplay'. node_modules/@types/three/three-core.d.ts(7801,23): error TS2304: Canno ...