Using Angular 6 to implement a select dropdown within a *ngFor loop in

My Angular 6 component fetches an observable list of users and displays a table using the *ngFor statement. Each row has a submit button that calls a function passing in the user for that row. This functionality works correctly.

Now, I want to add a select option to each row with a list of actions the user wants to perform. How can I retrieve the value of the selected action for the specific row?

Here is an example of the JSON object returned from an HTTP call:

[
  {
    "userId": 1,
    "username": "user1",
    "firstName": "f1",
    "lastName": "l1",
    "active": true
  },
  {
    "userId": 2,
    "username": "user2",
    "firstName": "f2",
    "lastName": "l2",
    "active": true
  }
]

In the component.ts file, I subscribe a property of type UserSearchModel[] to the JSON response and create a function for the table to call:

users$: UserSearchModel[];

submituseraction(user: UserSearchModel) {
    console.log(user.userId);
  }

Here is the model:

export class UserSearchModel {
    userId: number;
    username: string;
    firstName: string;
    lastName: string;
    active: boolean;   
}

In the HTML, I have the following code for displaying and submitting the data:

  <tr *ngFor="let user of users$">
    <td>{{ user.username}}</td>
    <td style="word-break: break-all">{{ user.firstName }}</td>
    <td style="word-break: break-all">{{ user.lastName }}</td>
    <td>{{ user.active }}</td>
    <td class="text-nowrap">
      <select name="usersearchactions" id="usersearchactions" title="Actions">
        <option value="0">Update User Info</option>
        <option value="1">Update Email</option>
        <option value="2">Reset Password</option>
        <option value="3">Notification Settings</option>
        <option value="11">Research</option>
      </select>
      <button (click)="submituseraction(user)" class="btn btn-primary btn-xs" type="submit">GO!</button>
    </td>
  </tr>

While everything is functioning correctly so far, I am struggling to retrieve the selected action for each user in my submituseraction method. I tried updating the UserSearchModel to include a new UserAction[] array that is populated with my list, but it did not work as expected. Any guidance on solving this issue would be greatly appreciated.

If there are any other significant errors in my code or approach, please advise as I am a beginner in Angular. Thank you.

Answer №1

To implement the functionality, insert an Angular variable declaration (#foo) within the select tag. Then, pass its value to the submituseraction function along with the user parameter.

<select #actions name="usersearchactions" id="usersearchactions" title="Actions">
  <option value="0">Update User Info</option>
  <option value="1">Update Email</option>
  <option value="2">Reset Password</option>
  <option value="3">Notification Settings</option>
  <option value="11">Research</option>
</select>
<button (click)="submituseraction(user, actions.value)" class="btn btn-primary btn-xs" type="submit">GO!</button>

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

React error: The module "react-router-dom" does not have a member named "useNavigate" available for export

I'm attempting to include useNavigate for use as outlined in the top answer here: react button onClick redirect page import { useNavigate } from "react-router-dom"; However, I am encountering this error: export 'useNavigate' (impo ...

When attempting to run npm install for @types/jquery, an error is returned stating "Invalid name: @types/jquery"

npm install @types/jquery npm ERR! Windows_NT 10.0.10586 npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-c ...

I encountered an error with the TS1003 code in Angular because an identifier was expected on the throw import statement. Upon further investigation, I realized that the issue originated from

I came across this piece of code: import { Observable, throw} from 'rxjs'; An error message popped up saying identifier expected: ERROR in config/config.service.ts(3,22): error TS1003: Identifier expected. The error appears to be related to ...

Experiencing unexpected behavior with Next.JS getStaticProps functionality

I am currently working on a website where I want to display dynamic feedback as cards. However, my fetchData variable within the Home function is always returning undefined. Here's the code snippet I have tried: import UserCard from "../component ...

``There seems to be a problem with the ngb time picker when using the up and

Currently, I am utilizing Bootstrap 4 and NG Bootstrap time picker for a project in Angular 10. Despite correctly adding all the code, I have encountered an issue where the up and down arrows on the time picker are not functioning as expected. Below is a s ...

Create a scrollable horizontal list of items

I am encountering an issue with my mat chip list in Angular Material. I have a mat chip list filled with mat-chips that I want to display in a single row. If there are more items than can fit on the screen, I would like the area to be scrollable horizonta ...

Harnessing the Power of FormControlName and Labels in Angular 6

In my project using Angular 6 and reactive forms, I have a grid with a Detail button that opens a modal window displaying student information. However, when implementing the HTML for the dialog box as shown below, I encountered an error message stating: No ...

Vue - Troubleshooting why components are not re-rendering after data updates with a method

Check out this simple vue component I created: <template> <div class="incrementor"> <p v-text="counter"></p> <button v-on:click="increment()">Increment</button> </div> </template> <script lan ...

What is the reason the server is not receiving the cookie?

I am currently running a nodejs express application on a server with two endpoints: POST /session - used to send back the cookie GET /resource - used to check if the cookie is sent back, returning 401 not found if it's not On the frontend, hosted on ...

Is the user's permission to access the Clipboard being granted?

Is there a way to verify if the user has allowed clipboard read permission using JavaScript? I want to retrieve a boolean value that reflects the current status of clipboard permissions. ...

Create an interface property that can accommodate various disparate types

In a React component, I am looking to use an external type (from react-hook-form) that can accommodate 3 specific types representing an object with form values. I initially thought about using a union type for this purpose, but encountered issues when pas ...

What is the best way to take any constructor type and transform it into a function type that can take the same arguments?

In the code snippet below, a class is created with a constructor that takes an argument of a generic type. This argument determines the type of the parameter received by the second argument. In this case, the first parameter sets the callback function&apos ...

I desire to obtain an image from a different webpage

I am a beginner in the world of Ionic/Angular. On my edit profile page (which is a separate page), I have the ability to change my profile picture. When I make this change, it should automatically reflect on my main profile page, which is on another page. ...

What is the correct regex expression for validating decimal numbers between 1.0 and 4.5?

I'm having trouble creating an expression to validate numbers between 1.0 to 4.5 accurately. The current expression I'm using is not working as intended: /^[1-4]{0,1}(?:[.]\d{1,2})?$/ The requirement is to only allow values between 1.0 to ...

Issue with Nuxt: Property accessed during rendering without being defined on the instance

As I attempt to create cards for my blog posts, I encountered an issue with a Post component in my code. The cards are displaying like shown in the picture, but without any text. How do I insert text into these cards? Currently, all the text is within attr ...

"Enhancing User Experience with Hover States in Nested React Menus

I have created a nested menu in the following code. My goal is to dynamically add a selected class name to the Nav.Item element when hovering, and remove it only when another Nav.Item is hovered over. I was able to achieve this using the onMouseOver event. ...

"Exploring the incredible powers of Ionic2, Angular2, HTTP requests, and

Despite all the research I've done on observables, I still struggle to grasp how they function. The HTTP request code snippet is as follows: import { Component, OnInit, Injectable } from '@angular/core'; import { Http, Response, Headers, R ...

Unable to locate the type definition file for 'zen-observable'

While working with Ionic 3, I decided to use the AWS default template and encountered an error: > ionic start app0 aws // aws is a default starting app in Ionic3 > cd app0 > ionic serve However, when I tried to serve the application, I received ...

Calculating the sum of values in a JSON array using a specific parameter in Typescript

A flat JSON array contains repetitive identifier, categoryId, and category: data: [ { "identifier": "data", "categoryId": "1", "category": "Baked goods", "product": "Aunt Hattie's", "price": "375" } ...

typescriptUsing redux: prevent parent component from accessing redux props

I'm currently using redux and typescript in my webapp project. What's the best approach for defining props in a component that receives redux-actions through @connect, as well as props from its parent? // mychild.tsx export namespace MyChildCom ...