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

Can functions be used as keys in a collection in JavaScript's map?

Using functions as keys in JavaScript can be tricky because for js objects, functions are converted to their "toString" form. This poses a problem if two functions have the same body. var a = function() {}; var b = function() {}; var obj={}; obj[a] = 1; o ...

Is it possible to center-align the text in a Material-ui TextField and enforce a minimum numerical value at the same time?

I'm facing an issue with trying to center align the text inside the TextField and also set a minimum value of 0. It seems like I can only achieve one or the other, but not both simultaneously. I referred to the material-ui page on TextField for help, ...

Unable to load the .js file within the Angular module

I am facing an issue with my Angular sidebar component that is trying to load a local script called sidebar.js. I have the following code in src\app\sidebar\sidebar.component.ts: ngAfterViewInit(): void { const s = document.createEleme ...

Angular's Motion Module

Incorporating Angular-5 into my project has introduced a plethora of animations on various pages. While the utilization of jQuery provides a straightforward approach for adding and removing classes to DOM elements, it is frequently advised against using jQ ...

A function that retrieves the empty values from an array and returns undefined if there

After undergoing a time-consuming process, the sample below shows that the array values are returned empty. function myFunction() { let myArray = []; let pastArray = [1, 2, 6, 7, 8, 1, 9, 6, 0] pastArray.forEach(item =>{ setTimeout(function(){ myA ...

What is the best way to extract the variable inside a script tag as a JSON value?

Hey, I need help figuring out how to convert a JavaScript variable into a JSON value using Python with the help of libraries like BeautifulSoup and requests. I attempted to solve this issue by following a similar topic on Stack Overflow, but unfortunately ...

Saving asp.net strings in different formats to datetime fields in a database

Can someone please assist me with saving the string value of textbox to the database as a datetime, and for updating/editing purposes, display it again in the textbox as a string? The reason for this is that the datetime input will be copied from Outlook a ...

The values in my JavaScript don't correspond to the values in my CSS

Is it possible to retrieve the display value (display:none; or display:block;) of a div with the ID "navmenu" using JavaScript? I have encountered an issue where I can successfully read the style values when they are set within the same HTML file, but not ...

Show basic HTML elements on a single page of an Angular Material web application

I am working on an Angular (6) web app with a customized theme using Angular Material. Currently, I am trying to incorporate a popup dialog that includes basic HTML elements like checkboxes, buttons, and inputs. Even though I have successfully displayed ...

Show or hide the right element when clicked using ng-show in AngularJS

My goal is to toggle elements based on which one is clicked, not all at once. For instance, if I have 3 form elements and 3 buttons, when I click on button 1, I only want to toggle the corresponding form element. Here is my current code snippet: In Angu ...

The Cross-Origin Resource Sharing request using the PUT method has been denied due to restrictions set by the

I am currently using CORS requests to communicate between my client and server located on different domains. I have configured my Apache HTTP server to use SSL in the following manner: // Utilizing AJAX withCredentials=true (sending cookies, allowing SSL ...

Facing an issue with the ng2-carousel component where the left and right arrow icons are

Currently employing ng2-carouselamos Visit the ng2-carouselamos npm page here After duplicating the provided HTML template, I have encountered issues with clickable events not functioning properly. The absence of a TypeScript file in the documentation ma ...

What is the correct method for adjusting the height properties of an element?

I'm trying to adjust the height of my div using the code below var heightMainDiv = window.innerHeight - 50; var myDiv = $("#main_content")[0]; myDiv.clientHeight = heightMainDiv; myDiv.scrollHeight = heightMainDiv; However, the values of clientHeigh ...

Getting the ID of a select input option in Vue.js using FormulateInput

Recently, I've been working with a FormulateInput select component that looks like this: <FormulateInput name="broj_zns-a" @change="setZns" :value="brojZnsa" type="select" label="Broj ZNS- ...

What causes a slow disappearance of both the form element and its child elements when the visibility attribute is set to hidden on the

Have you ever noticed that the child elements of an element form hide slowly when using visibility:hidden, but hide quickly when using display:none? This slow hiding can negatively impact user experience. I tried to find information on this issue, but eve ...

Show Firebase data on Angular 6 mat-card in a randomized sequence when the page loads or refreshes

Is it possible to display cards in a random order when the value of a form changes or when the page is refreshed, while fetching data from Firebase? Below is my Component Template: <ng-container *ngFor="let geoToDisplay of geosToDisplay | async"> ...

What steps should be taken to incorporate a user input space similar to the one found in the Wordpress new post section

I am looking to incorporate a user input section on my website similar to the one found in WordPress for creating new posts. I would like this area to have all of the same tools available, such as adding hyperlinks, bolding text, and uploading images. Ca ...

The output from the Compute function is not showing up in the TextBox as expected

I'm currently working on an HTML page that contains two textboxes and a button. I've created a Compute function to display the result in one of the textboxes, but unfortunately, it's not functioning as expected. No alerts are appearing on th ...

What is the best way to include additional columns in a multiselect dropdown using jQuery select2?

I have implemented a multiselect dropdown feature using the jQuery select2 JavaScript library. The list items in this dropdown pertain to various medical drugs. I am looking to enhance this feature by adding a new column next to each selected drug, where ...

Exploring the impact of JavaScript tags on website performance in accordance with W3

While researching website optimization strategies today, I came across an article discussing the benefits of moving JavaScript scripts to the bottom of the HTML page. I am curious if this approach aligns with W3C's recommendations since traditionally ...