Angular Iterate Array Forms

Is there a way to iterate my rows based on user input? For example, if the user enters 2 values, I need to display 2 rows. How can I achieve this using FormArray?

setCount(count:any){
    console.log(count);
    this.count = count;
    this.countArray = Array(parseInt(count)).fill(0).map((x,i)=>i);

  }


  <mat-form-field class="full-width">
                                <mat-label>Qty</mat-label>
                                <input matInput type="number" formControlName="qty" value="0" (click)="setCount($event.target.value)">
                            </mat-form-field>


<tr *ngFor="let Array of Array.controls; let i = index;" [formGroupName]="i">
                            <td>
                                
                            </td>
                            <td>
                                <input type="text" formCOntrol="Number" class="form-control" style="width:700px">
                                </td>
                        </tr>

Here is an illustration:

https://stackblitz.com/edit/angular-pgwv3t

Answer №1

Here is a different approach

  formGroup: FormGroup;

  get itemsArray(): FormArray {
    return this.formGroup.get('items') as FormArray;
  }

  constructor(private formBuilder: FormBuilder) {}

  ngOnInit() {
    this.formGroup = this.formBuilder.group({
      itemCount: [0],
      items: this.formBuilder.array([]),
    });
    this.formGroup.get('itemCount').valueChanges.subscribe((result) => {
      for (let j = this.itemsArray.length; j < result; j++) {
        this.itemsArray.push(this.addItems());
        console.log(this.itemsArray);
      }
    });
  }

  addItems(): FormGroup {
    return new FormGroup({
      itemValue: new FormControl(0, { validators: [Validators.required] }),
    });
  }

check out the example code

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

What is the best way to obtain a signed cookie in aws-sdk-js-v3?

I am looking to utilize signed cookies for accessing private content stored on S3 using CloudFront for CDN. I am struggling to identify the appropriate commands to generate signed cookies in aws-sdk-js-v3. According to the updated SDK documentation, it sh ...

Utilizing Angular 6 for mapping objects in reactive forms

I'm having trouble mapping the value of my hero object from a Reactive form in Angular. Below is the code snippet from my hero-add.component.ts file: import { Component, OnInit, Input } from '@angular/core'; import { Hero } from '../He ...

Creating dynamic lists in Angular with ngFor: A step-by-step guide

I am currently working on an Angular 7 application and have a component that retrieves a JSON array. @Component({ selector: 'app-indices-get', templateUrl: './indices-get.component.html', styleUrls: ['./indices-get.component ...

Having issues with importing momentjs by reference in TypeScript with amd configuration

I'm puzzled by the difference in behavior between these two snippets: import * as moment from "../Typings/moment"; One works, while this one doesn't: /// <reference path="../Typings/moment.d.ts" /> import * as moment from "moment"; It t ...

Sending file URL to Angular component

Hey there, I am looking to relocate an existing link within my Angular 4 project. For instance, the link I want to move is "". I have attempted to do so in my router configurations: path: 'test', component: TestComponent, children: ...

How can you connect one data field to another within Angular?

Angular offers a convenient method for binding the value of an HTML element to a data field. For example, you can achieve this with the following code: <input name="firstName" [(ngModel)]="firstName"/> This means that any text en ...

CORS policy has blocked the Node.JS OvernightJS Express CORS XMLHttpRequest request

I have a back-end API created using Node.js and Typescript that is listening on localhost:3001. Additionally, I have a front-end application built with Angular and Typescript that is listening on localhost:4200. Currently, I am attempting to upload an ima ...

Fetching HTML files directly after building Angular (Tips for Developing Chrome Extensions)

Currently, I am in the process of creating a custom Panel within Chrome DevTools using Angular and Typescript. Through my efforts, I have successfully implemented a new Panel by utilizing the code snippet provided below: chrome.devtools.panels.create(&ap ...

How to Retrieve a File Using Angular 2

Currently, I am trying to download a file in pdf format using Angular 2. For this purpose, I have incorporated FileSaver.js to facilitate the saving of the file as a pdf. (response) => { var mediaType = 'application/pdf'; let pdfConte ...

Redirecting with response headers in Next.js

Objective: The Goal: Clicking a button on a page should send a request to the controller. The controller will then set a cookie, and upon receiving the response, redirect the page to another page, such as the about page. Directly Calling API route from th ...

Is TypeScript failing to enforce generic constraints?

There is an interface defined as: export default interface Cacheable { } and then another one that extends it: import Cacheable from "./cacheable.js"; export default interface Coin extends Cacheable{ id: string; // bitcoin symbol: stri ...

Master the art of properly switching on reducer-style payloads in Typescript

Currently, I am dealing with two types of data: GenArtWorkerMsg and VehicleWorkerMsg. Despite having a unique type property on the payload, my Searcher is unable to differentiate between these data-sets when passed in. How can I make it understand and dis ...

Why do the RouteConfig and classes necessitate the inclusion of a service and router in their constructors?

While working with a sample code in the Angular2 framework, specifically the Heroes sample, I have encountered something that I am struggling to understand. What determines the order of dependencies in the constructor, like Router, Service or vice versa? ...

Utilizing dynamic arguments in TypeScript to recycle types

Can I accomplish this with TypeScript? Here is the source code I currently have: interface FormStore<T> { type: T; } interface Form<T> extends FormStore<T> { email: T; phone: T; password: T; } interface FormState<R> { fo ...

Add TypeScript typings for npm utility manually by incorporating type definitions

I'm in the process of incorporating TypeScript into an existing JavaScript project, and I'm currently facing the challenge of adding typings to an npm module that lacks type definitions, which I anticipate will be a common issue. When I try to i ...

Creating a cucumber feature file from an Excel sheet or any other type of file: A step-by

I currently have an excel sheet containing various scenarios that I need to convert into a feature file. Can you assist me in accomplishing this task? Do you know of any plugins that can help streamline this process? Any guidance would be greatly apprecia ...

Tips for showcasing the contents of a file on a website

Greetings! I am a newcomer to the world of web development and I am seeking a method to showcase file content on a webpage. Presently, I have succeeded in loading text file content and displaying it in a large text box. However, I am now interested in di ...

routerLinkActive maintains its active state even after another link has been clicked

<ul> <li routerLinkActive="active"><a routerLink="/">One</a></li> <li routerLinkActive="active"><a routerLink="/somewhere">Two</a></li> </ul> Upon clicking the link Two, both links are being hi ...

Dynamically assign values to object properties of varying data types using indexing

My goal is to dynamically update one object using another object of the same type. This object contains properties of different types: type TypeOne = 'good' | 'okay'; type TypeTwo = 'default' | 'one'; interface Opt ...

Angular indicates that there is a problem with the property 'x' as it is not found in the type 'y[]'

I am trying to display the details of users using the *ngFor directive, but encountered an error earlier. Here is the code snippet: this.users=[ // first user { firstName: 'John', lastName: 'Doe', c ...