How can I prevent buttons from being created using ngFor in Angular?

I need help with creating an HTML table that includes a cell with a button and a dropdown generated using ngFor. How can I disable the buttons (generated via ngFor) if no value is selected from the dropdown? Here's what I have tried so far:

In my AppComponent, I have the following:

ts

customers: Array<Object> = [];
level: string;

changedvalue(event: Event) {
   const value = (<HTMLSelectElement>event.target).value;
   this.level = value;
  }

html

<tbody>
<tr *ngFor="let customer of customers">
     <td> {{ customer.uid }} </td>

     <td> {{ customer.name }} </td>

     <td> {{ customer.level }}</td>

     <td>
     <select (change)="changedvalue($event)" class="form-control" name="level">
        <option  hidden selected> -- select an option -- </option>
        <option>Level 1</option>
        <option>Level 2</option>
     </select>
     </td>

    <td><button [disabled]=!level >Send</button></td>

</tr>
</tbody>

The issue with this code is that it enables all the buttons if any dropdown has a selected value. What I want is to only enable the button in front of each individual dropdown. How can I connect each button to its respective dropdown created using ngFor?

Answer №1

It is important to store a value within the customer so that each iteration will have its own level variable. Additionally, I have updated the method name to adhere to coding conventions.

<tbody>
    <tr *ngFor="let customer of customers">
         <td> {{ customer.uid }} </td>

         <td> {{ customer.name }} </td>

         <td> {{ customer.level }}</td>

         <td>
         <select (change)="onLevelChange($event, customer)" class="form-control" name="level">
            <option  hidden selected> -- select an option -- </option>
            <option>Level 1</option>
            <option>Level 2</option>
         </select>
         </td>

        <td><button [disabled]=!customer.level >Send</button></td>

    </tr>
</tbody>
customers: Array<Object> = [];

onLevelChange(event: Event, customer) {
   const value = (<HTMLSelectElement>event.target).value;
   customer.level = value;
   // if compiler complains as "there is no level property of customer"
   // you can do following
   // customer['level'] = value;
}

Answer №2

Here's a suggested approach:

Manually add a level to your customer model and follow these steps:

<tbody>
<tr *ngFor="let customer of customers">
     <td> {{ customer.uid }} </td>

     <td> {{ customer.name }} </td>

     <td> {{ customer.level }}</td>

     <td>
     <select (change)="customer.level = !customer.level" class="form-control" name="level">
        <option  hidden selected> -- select an option -- </option>
        <option>Level 1</option>
        <option>Level 2</option>
     </select>
     </td>

    <td><button [disabled]=!customer.level >Send</button></td>

</tr>
</tbody>

Answer №3

If you want to customize your customers object, you can add a custom property to it.

To see this concept in action, check out the live example on StackBlitz: https://stackblitz.com/edit/angular-2m8ns7?file=src%2Fapp%2Fapp.component.ts

Here is an example code snippet demonstrating how to toggle a status for each customer:

<div *ngFor="let c of customers; let i = index">
  <span>{{c.name}} {{c.surname}} | Is Enabled? : {{c.isEnabled}}</span> 
  <button (click)="toggleMe(i)">Toggle Status</button>
</div>

Included below is the TypeScript code implementing this functionality:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  public customers : any[] = [];

  constructor(){
     this.customers = [
    {
      name: "Jhon",
      surname: "Cena",
      isEnabled: false
    },

    {
      name: "Mike",
      surname: "Mya",
      isEnabled: false
    },

    {
      name: "Sandy",
      surname: "Rivers",
      isEnabled: false
    }
  ];
  }

  toggleMe(i){
    this.customers[i].isEnabled = !this.customers[i].isEnabled;
  }
}

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

Disabling iframe javascript timers when iframe is no longer in the user's view

Currently, I am working on a blog post that will showcase various HTML5/Javascript animations through multiple <iframe> sections. These animations utilize methods such as requestAnimationFrame() and/or setInterval(). Due to limitations within the blo ...

From HTML to Python to Serial with WebIOPi

I am facing a dilemma and seeking help. Thank you in advance for any guidance! My project involves mounting a raspberry pi 2 b+ on an RC Crawler rover, utilizing WebIOPi for the task. However, I am encountering challenges and unable to find useful resourc ...

Is there a way for me to show "No data" when the json response in vue js is empty?

Is it possible to display a message like "No search results" when there is no data available? I am new to this and only have basic understanding. Can someone guide me on how to achieve this? Example of my JSON data when it's empty: { "status": true ...

Material UI TreeView: Organize and present node data with multiple columns in a tree structure

const treeItems = [ { id: 1, name: 'English', country: 'US', children: [ { id: 4, name: 'Spring', country: 'Uk', ...

What could be causing JSON.parse to encounter errors when parsing a string array?

Within the following function, I am utilizing JSON.parse() on specific string arrays saved in window.sessionStorage. This allows me to apply methods like .map(). window.sessionStorage = { myArray1: "["805746|search|4","980093062|search|0","980113648| ...

What are the steps to integrate material-ui with styled-components effectively?

import styled from "styled-components"; import Button from "@material-ui/core/Button"; export const StyledButton = styled(Button)` margin: 20px; `; I'm having trouble adjusting the button styling. How can I add a margin to the ...

Conceal a division on a webpage according to the URL of the specific

<script> function hideSearchField() { if (/menu/.test(window.location.href)) { document.getElementById('searchfield').style.display = 'none'; } } hideSearchField(); </script> I am trying to accomplish this using Jav ...

What is the best way to switch from http to https in a React application?

When performing audits in Chrome, I encountered a net::ERR_EMPTY_RESPONSE error because Lighthouse was not able to consistently load the requested page. Google developers have recommended configuring my server (possibly node.js) to redirect from http to ht ...

How to store an imported JSON file in a variable using TypeScript

I am facing a challenge with a JSON file that stores crucial data in the following format { "login": { "email": "Email", "firstName": "First name", "lastName": "Last name", ...

Having trouble grasping the error message "Uncaught Typerror Cannot Read Property of 0 Undefinded"?

As I embark on creating my very first ReactJS website with Node in the back-end, I encountered an issue in fetching and printing data. While I successfully displayed the names, pictures, and emails of project members from the server, I faced an error when ...

Incorporate keyboard input functionality into an object wrapper

Adding typing to a class that encapsulates objects and arrays has been a bit tricky. Typing was easily implemented for objects, but ran into issues with arrays. interface IObject1 { value1: string, } interface IObject2 { myObject: IObject1, ...

Dropdown with no selected option

Having some trouble with the p-dropdown element in Angular5 and primeng library. Specifically, when dealing with a large entity called Consignment that has multiple fields, I notice that the selected values on several p-dropdown elements (in this case, the ...

Is there a way to display the JavaScript widget exclusively on the homepage or main page

How can I limit the display of a Twitter widget on my blog page to only show on the main page and hide it when visitors navigate to sub-pages or individual blog entries? ...

Leveraging the power of React's callback ref in conjunction with a

I'm currently working on updating our Checkbox react component to support the indeterminate state while also making sure it properly forwards refs. The existing checkbox component already uses a callback ref internally to handle the indeterminate prop ...

Refresh the screen after 10 seconds

Apologies if I'm not explaining this well in advance. I am looking to create a dynamic webpage using JavaScript that automatically updates every 10 seconds. Does anyone have an example code snippet for this? **Specifically, allow ...

Tap and hold with Zepto

I've been on the hunt for a Zepto plugin that can handle a longClick event. While Zepto already supports longTap, which is perfect for mobile devices, I need something specifically for desktop browsers when a user clicks and holds. It's also impo ...

Encountered an issue in React Native/Typescript where the module 'react-native' does not export the member 'Pressable'.ts(2305)

I have been struggling to get rid of this persistent error message and I'm not sure where it originates from. Pressable is functioning correctly, but for some reason, there is something in my code that doesn't recognize that. How can I identify t ...

Is it possible to utilize Vue.js' v-if directive to validate if a certain value is present within an array

In my form, I have a checkbox and I want to be able to use v-if directly to display or hide sections based on the selected checkbox values. Can this be done using v-if, or do I need to use watch:? ...

Error: Variable 'err' is undefined in Node.js

Why am I getting a ReferenceError: err is not defined even though it is supposed to be defined here? const sampleObject = require('./sampleObject'); const sampleModel = (callback) => { if (true) { sampleObject.sampleRetrieval(err ...

Using Material UI Slider along with Typescript for handling onChange event with either a single number or an

Just diving into Typescript and encountered an issue with a Material UI Slider. I'm trying to update my age state variable, but running into a Typescript error due to the typing of age being number and onChange value being number | number[]. How can I ...