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

A guide to configuring VSCode to recognize the DefinitelyTyped global variable (grecaptcha) within a Vuejs 3 TypeScript project

I have recently set up a new project using Vue.js 3 and TypeScript by running the command npm init vue@latest. I now want to integrate reCaptcha v2 into the project from scratch, without relying on pre-existing libraries like vue3-recaptcha-v2. Instead of ...

The patchState function is iterated within the NGRX component-store effect

My program is stuck in an infinite loop and I can't figure out why. interface LatestAppointmentsWidgetState { loading: boolean; page: number; pagedData: Paged<Appointment>; } @Injectable() export class LatestAppointmentsWidg ...

Unnecessarily intricate: A Comparison and Enumeration of Elements in Arrays

I am facing a challenge with organizing arrays that represent categories and subjects. Each array represents a category, while each item within the array is a subject. For example: 4 Categories with Subjects ['A','B','D'] [&a ...

Dynamically loading external JavaScript for an Angular component and triggering the window load event

I am currently dealing with an external javascript file that I only want to be included on a specific component, so the approach I'm taking involves dynamically loading it. I came across this answer that explains exactly how to achieve this. The prob ...

Logging in with an External Provider using ASP Core, Identity Server 4, and Angular 2

I have successfully configured an ASP Core App with Identity Server 4 to enable token-based authentication for an Angular 2 SPA. In order to enhance the login process, I am looking to integrate External Providers such as Google and Facebook. However, I am ...

The Datatable is displaying the message "The table is currently empty" despite the fact that the rows have been loaded through Angular

My experience with displaying a data table in Angular was frustrating. Even though all the records were present in the table, it kept showing "no data available." Additionally, the search function refused to work as intended. Whenever I tried searching for ...

Having trouble passing a React Router Link component into the MuiLink within the theme

The MUI documentation explains that in order to utilize MuiLink as a component while also utilizing the routing capabilities of React Router, you need to include it as a Global theme link within your theme. An example is provided: import * as React from & ...

Retrieving a text file in Angular 8 using an authentication header

I'm attempting to create a download link that allows users to download a record in .txt format. Initially, I used a simple <a> tag: <a href="http://localhost:8080/service/api/downloadFile?fileType=daily&trsDate=20190918">download< ...

What are some techniques for breaking down or streamlining typescript code structures?

Within my TypeScript class, I have a skip function. In the interface, I've specified that the data is coming from the backend. Now, on the frontend, I want to be able to rename the backend variables as demonstrated below. There are multiple variables ...

What is the process for removing a particular file from my bundle?

I am currently utilizing webpack to build my angular2/typescript application and have successfully generated two files, one for my code and another for vendors. However, I am in need of a third file to separate my config (specifically for API_ENDPOINT) whi ...

Managing clearing values/strings for different input types like text/password upon form submission in Angular2

Here is a code snippet for an HTML form: <div> <form class="form-horizontal" role="form" (ngSubmit)="createUser(Username.value, Password.value)"> <div class="col-xs-6 col-sm-6 col-md-6 col-lg-6"> <input type="text" class=" ...

Unable to receive response from API in Ionic 4 Angular. Postman shows correct response

Ionic v4 Controller for Items: view image description here Response in DevTools -> I always receive data from the database - web application functions correctly view image description here Response from Postman: view image description here Please help ...

Typescript: object containing at least one property with the type T assigned

Is there a method to write the HasNumber interface in Typescript without receiving an error due to the fact that the HasNumberAndString interface includes a property that is not of type number? I am looking for a way to require the HasNumberAndString int ...

Using TypeScript TSX with type parameters

Is it possible to define type parameters in TypeScript TSX syntax? For instance, if I have a class Table<T>, can I use something like <Table<Person> data={...} /> ...

Personalizing the mat-checkbox

I'm trying to customize the checked icon in angular material mat-checkbox. Currently, it displays a white tick icon inside a colored background box, but I want to replace the tick with a cross when it is checked. After spending all day searching, I ha ...

The properties required for type 'Subscription' are not present

I encountered an issue in my IDE while trying to run the following code. Within my component, I am making a call to a service in the ngOnInit method to fetch some data. This service, in turn, calls another service to gather additional information before f ...

Strategies for managing various errors that can arise when multiple Angular components are subscribed to a single state

My Angular application is facing a dilemma with three components at play: Component #1: Shows a list of items Component #2: Displays recently used items Component #3: Exhibits the current item For now, let's assume they're all visible on the sa ...

Unable to sign out user from the server side using Next.js and Supabase

Is there a way to log out a user on the server side using Supabase as the authentication provider? I initially thought that simply calling this function would work: export const getServerSideProps: GetServerSideProps = withPageAuth({ redirectTo: &apos ...

I'm struggling to get the Bootstrap collapse navbar-collapse feature to work in my Angular

My attempt at implementing the bootstrap collapse navbar-collapse feature in my Angular 8 project seems to be not working correctly after compilation. I have already installed: bootstrap - 4.3.1 and made changes to the angular.json file. I also have jquery ...

Unable to download essential dependencies using NPM

After cloning a repository for a MEAN stack application, the first step was to run npm install. The installation process resulted in: added 1580 packages from 1887 contributors and audited 15249 packages in 281.586s found 18 vulnerabilities (5 low, 12 mod ...