Unlock the potential of ng-for to dynamically generate input boxes and checkboxes!

In this Angular application, my requirement is to repeat the elements inside a div based on the number entered in an input box (record.accountRoles).

<!-- Input Box -->
 <div class="form-group">
   <label for="name">Enter the number of accounts</label>
   <input type="text" class="form-control" [(ngModel)]="record.accountRoles" name="accountsRoles" required>
 </div>


<!-- Div Elements to Repeat -->
 <div *ngFor="let i of record.accountRoles.length">
   <label for="name">Account ID</label>
    <input type="text" class="form-control" [(ngModel)]="record.roles[i].accountid" name="accountid" required> 

    <mat-checkbox [(ngModel)] = "record.roles[i].role"> 
     <label>IT Admin</label> 
    </mat-checkbox>
  </div>

This is how the record variable is initialized:

 record = {firstName:null,lastName:null,emailAddress:null,accountRoles:null,roles:[{accountid:null,role:null}]};

Answer №1

Revise your HTML to:

  <div class="form-group">
       <label for="name">Please input the number of accounts</label>
       <input type="text" class="form-control" [(ngModel)]="record.accountRoles" (change)="updateAccounts()" name="accountsRoles" required>
     </div>


    <!-- These div elements need to be repeated -->
     <div *ngFor="let item of record.roles">
       <label for="name">Account ID</label>
        <input type="text" class="form-control" [(ngModel)]="item.accountid" name="accountid" required> 
<mat-checkbox [(ngModel)] = "item.role"> 
             <label>IT Administrator</label> 
            </mat-checkbox>
      </div>

If you require the index for some purpose, use:

*ngFor="let item of record.accountRoles; let i = index"

Modify your component to:

   record = {firstName:null,lastName:null,emailAddress:null,accountRoles:1,roles:[{accountid:null,role:null}]};

updateAccounts () {
  this.record.roles = [];

  for(let i = 0 ; i< this.record.accountRoles; i++)
    this.record.roles.push({accountid:null,role:null}); 
  }

https://stackblitz.com/edit/angular-nzuc9h?file=src%2Fapp%2Fapp.component.html

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

Develop a personalized React route component using TypeScript. The error message "Property 'path' does not exist on type... RouteProps" is displayed

I am currently working on creating my own route component using React. Although I am new to TypeScript, I believe that is the root cause of the issue I am facing. import * as React from 'react' import { ApplicationState } from '../../store& ...

My goal is to store the received response in an array within an object

const data = [ { id: 1, user_name: 'john', phone_number: 5551234567 }, { id: 2, user_name: 'jane', phone_number: 5559876543 }, { id: 3, user_name: 'doe', ...

Storing Firebase Auth User references in a Firestore document: Tips and Tricks

I have developed an application that allows users to register and login, using Firebase Auth for authentication. In addition to Firebase Auth, I also utilize Firestore to manage multiple collections like "Requests" and "Offers". A user authenticated with ...

Page reloads are disabled when Chrome devtools debugger is paused in a React app

Currently, I am in the process of troubleshooting a React application that was created using create-react-app. Whenever I attempt to reload the page while paused on a breakpoint, it results in the page stalling. The screen goes blank and is unresponsive t ...

Using jQuery to retrieve the unique identifier of an element and checking if it matches a certain value before including the link

I'm currently using this code to retrieve values from a database and then add them to a form. The initial part appends the name of the Firewall and includes the unique ID in the element's id. if (value.type == 'Firewall') { $(' ...

How can we ensure that the slider thumb label is always shown in Angular 16 Material components?

Is there a way to display the thumb label constantly on a material slider? The solution mentioned above does not seem to work with Angular 16 material UI slider. Could you kindly offer an alternative solution for this issue? ...

Encountering an issue with importing mongoose models while trying to create a library

I've been working on creating a library of MongoDB models and helper classes to be shared as an npm module with the rest of my team. However, I'm facing an issue with the main code that I import from lib MongoConnector which processes configurati ...

Why are the HTML links generated by JS not opening in Chrome?

<a href='http://www.xyz.hu/xyz' alt='Kosár' title='Kosár'>Megtekintés</a> Additionally: - A setInterval function refreshes the sibling's content every second, although it should not affect this specific el ...

Elevate your frontend development game with the powerful combination of Vue js 3

I've been attempting to add this dependency, but I keep receiving an error message stating that it doesn't exist and Vue 3 is unable to resolve the component. Click here to visit the npm page for vue-phone-number-input Any assistance you can pr ...

Instructions for utilizing lodash or JavaScript to apply a filter to an object

Received this object from the Server: var data = { test1: { documents: [] }, test2: { documents: [{ vId: 'sdfas23', TypeId: '81', isDeleted: false }], answer: true }, test3: { documents: ...

Guide on incorporating mouse movement while the mouse button is held down in JavaScript

For my project, I want to activate the mouse move event only when the mouse button is held down. I specifically need the action "OK Moved" to be triggered only when both the mouse button is held down and there is mouse movement. This is the code that I h ...

`How can you effectively simulate class modules in Jest?`

Working with the amplitude module requires me to start by creating an instance of a class and then use its methods. Here's the initial code snippet: var Amplitude = require('amplitude'); const amplitude = new Amplitude(process.env.amplitude ...

Does C# have an equivalent to TypeScript's Never type?

Is there a C# equivalent for TypeScript's never type? I am curious about this. For example, in TypeScript, if I write the following code, I will get a build time error: enum ActionTypes { Add, Remove } type IAdd = {type: ActionTypes.Add}; t ...

The command "Npm Start Causes sleep is not accepted" just popped up

After cloning a React project from GitHub, I proceeded to run npm install, which successfully installed the node_modules folder. However, upon trying to run npm start, I encountered the following error: 'sleep' is not recognized as an internal or ...

What is the reason behind Express serving the static file through the router, while also causing the path to the scripts folder to

Directory Layout app ├── app.js ├── public │   ├── data │   │   └── data.json │   ├── index.html │   └── js │   ├── filter-list.js └── routes └── index.js Setting up ap ...

Is your idTabs design in need of some sprucing up

Just stumbled upon idTabs and trying to implement a basic one on my server. I've taken the code from the 'Usual' page, included the plugin file and jQuery, but all I'm seeing is... - Tab 1 - Tab 2 - Tab 3 This is tab 1. Seems like it& ...

Where can I find the JavaScript code that controls the button function?

Is there a method to identify the trigger that activates a button's specific action and page refresh, such as this example: <input type="submit" name="name" value="some value" id="mt1_main_btn" class="btn_next"> Simply copying the button does ...

Is there a way to automatically fill in a MUI textfield in a React Hook form with data retrieved from Firestore?

Utilizing React Hook Forms alongside MUI TextField components has been a productive challenge for me. I've been able to successfully fetch data from Firestore and aim to prefill the form with this retrieved information. Although I am employing useFor ...

Issue with Inline JS not functioning correctly in Flask when integrated with Bootstrap 5

I'm developing a Flask web app with Bootstrap 5 and attempting to incorporate inline JS, but it's not functioning as expected. Specifically, I'm trying to use a simple alert() component, but nothing is displaying on the page. Interestingly ...

Implementing stuck elements in a Collection using React Virtualized

Is there a way to make the content of a cell in a react-virtualized Collection stay fixed to one side while scrolling? I usually achieve this with position:sticky, but it doesn't seem to work for content within a Collection. I'm currently workin ...