Storing a variety of values within a formControl in Angular

I'm currently working on a form that involves managing an array of quantity materials in TypeScript. These materials can be added or removed from an inventory and are displayed in the HTML using ngFor. My goal is to allow the FormControl to accommodate multiple values based on the materials added, without knowing the exact number beforehand. The same challenge applies to distinguishing between new material codes and old material codes within the form. The code snippet below outlines my approach.

<div class="row" *ngFor="let material of materials">
  <mat-form-field class="col-md-4">
    <mat-select required placeholder="Select Material" formControlName="materials">
      <mat-option *ngFor="let object of objects" [value]="object">
        {{ object }}
      </mat-option>
    </mat-select>
  </mat-form-field>
  <mat-form-field class="col-md-4">
    <input matInput type="text" formControlName="new" />
    <mat-label>Code New Material</mat-label>
  </mat-form-field>
  <mat-form-field class="col-md-4">
    <input matInput type="number" formControlName="old" />
    <mat-label>Code Old Material</mat-label>
  </mat-form-field>
</div>
<div class="row mb-2 d-flex justify-content-center">
  <div class="col-xs-12 col-md-4 mb-2">
    <button
      mat-raised-button
      color="primary"
      class="btn bnt-primary btn-block"
      (click)="addMaterial()"
    >
      <mat-icon>add</mat-icon>
      <span> Add Material</span>
    </button>
  </div>
  <div class="col-xs-12 col-md-4">
    <button
      mat-raised-button
      color="warn"
      class="btn bnt-primary btn-block"
      (click)="removeMaterial()"
    >
      <mat-icon>remove</mat-icon>
      <span> Remove Material</span>
    </button>
  </div>
</div>

Here's how I'm handling this in my TypeScript file:

export class MaterialComponent implements OnInit {
  materials: number[] = [1];
  objects: string[] = ['MATERIAL 1', 'MATERIAL 2','MATERIAL 3', 'MATERIAL 4'];
  form: FormGroup;

  constructor(private formBuilder: FormBuilder) {}

  ngOnInit(): void {
    this.makeForm();
  }

  makeForm() {
    this.form = this.formBuilder.group({
      materials: [''],
      new: [''],
      old: [''],
    });
  } 

  addMaterial() {
    this.materials.push(1);
  }

  removeMaterial() {
    this.materials.pop();
  }
}

When I use

console.log(this.form.get('materials').value)
, it only retrieves the first value. How can I capture all the values for each input generated by ngFor?

Answer №1

If a user needs to add or remove materials by clicking a button, you can update a form control based on the elements in an array at that moment. This task can be accomplished by utilizing patch functionality on the form control after a push or pop operation.

   addMaterial(){
    this.materiales.push(1);
     //Update the desired formcontrol here as needed
     this.form.patchValue({
      materials: function (){
        let temp = "",
        this.materials.forEach(index,value){
           temp += value;
         }
        return temp;
      }
    });
    
  }
  removeMaterial(){
    this.materiales.pop();
    //Update the desired formcontrol here as needed
    this.form.patchValue({
      materials: this.materials
    });
  }

Learn more about Angular Reactive Forms

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

The server's response is unpredictable, causing Json.Parse to fail intermittently

I have encountered a strange issue that is really frustrating. It all started when I noticed that my Json.Parse function failed intermittently. Here is the code snippet in question: const Info = JSON.parse(response); this.onInfoUpdate(Info.InfoConfig[0]); ...

Issue with PrimeNG overlaypanel displaying error message "Functionality of this.engine.setProperty is not available"

After importing OverlayPanelModule as @NgModule in parent.module.ts, I added the following code in child.component.html: <p-overlayPanel [dismissable]="false" #overlay> Content </p-overlayPanel> However, upon testing, I encountered the error ...

Angular 2 ngSubmit triggers unexpectedly on occasions when it is not supposed to

Currently, I am working on developing an Ionic 3 application with Angular 2 and TypeScript. In the app, there is a form that is responsible for sending data to our server. The issue I am facing is that whenever I click on the following button: <butto ...

Issues with Next.js and Framer Motion

My component is throwing an error related to framer-motion. What could be causing this issue? Server Error Error: (0 , react__WEBPACK_IMPORTED_MODULE_0__.createContext) is not a function This error occurred during page generation. Any console logs will be ...

Angular: NaNa: Attempting to access a property of an undefined variable

I've encountered these errors although the values are displayed correctly in the browser. I'm unsure about how to resolve this issue. ERROR TypeError: Cannot read property 'length' of undefined ERROR TypeError: Cannot read property &ap ...

Quick method for importing components and modules

While developing my app using @angular/cli, I have noticed that as the app size increases, it becomes increasingly tedious to specify the paths for imports of components, modules, and scss files. For instance, when the component structure becomes deep, th ...

Designing a Test Specification for the @Input feature in Angular 2

@Input() public set isRunning(value: boolean) { if (!value) { this.cancelTimeout(); this.isDelayedRunning = false; return; } if (this.currentTimeout) { return; } ...

After updating the file path, the Next.Js module couldn't be located: Module not found – Unable to

After relocating the EmptyTable.tsx file from its original directory at views/forms-tables/tables/react-table/EmptyTable to a new location at components/Tables/EmptyTable, I encountered a persistent issue. Despite updating the import path in my code to mat ...

"Disabling Click Event on Sidebar Menu in Angular: A Step-by-Step Guide

I am working on an Angular project with a sidebar that I want to modify in order to disable click events on the menu items. My goal is to guide users through a specific flow without allowing them to navigate freely. However, simply disabling the [routerLin ...

Designing Angular 1 table row components with future migration to Angular 2 in consideration

Issue with AngularJS nested directives placement outside parent element Encountering the same challenge in my project using Angular 1.4, but I am also aiming to construct the rows as Angular 2 components which prevents me from using "replace: true". I am ...

Adding the ability to export CSV files from Bootstrap Table to an Angular 15 project

Struggling to incorporate the Bootstrap-table export extension into my Angular project without success so far. Visit this link for more information Any assistance or examples would be greatly appreciated. Thank you in advance! This is what I have tried ...

``Can someone provide guidance on how to showcase the validation check result for a text-field in the snackbar using Vuet

One of the challenges I'm facing in my project is implementing a validation function for the customer form. While using the vuetify validate method would be the easy way to go, I need to display the validation messages both as snackbar and next to eac ...

How to access objects in Angular2 without using pipe or ngFor

Suppose I have the following data in an asymmetric array: [{'name':'user','password':'123'},{'title':'officer','grade':'5','age':'5'}] which is obtained f ...

What is the best way to import multiple classes from a module folder in Angular2 using TypeScript?

In my Angular2 application, I have organized my modules as follows: /app /content /models resource.ts container.ts entity-type.ts index.ts /services /whatever ...

Formik button starts off with enabled state at the beginning

My current setup involves using Formik validation to disable a button if the validation schema is not met, specifically for a phone number input where typing alphabets results in the button being disabled. However, I encountered an issue where initially, ...

Add the slide number and total count in between the navigation arrows of the owl carousel

In my Angular application, I am utilizing an ngx owl carousel with specific configurations set up as follows: const carouselOptions = { items: 1, dots: false, nav: true, navText: ['<div class='nav-btn prev-slide'></div>' ...

"Improve your Angular ngrx workflow by utilizing the sandbox pattern to steer clear of

Currently, I'm trying to determine whether my implementation of the ngrx and sandbox pattern is effective. Here's the issue I'm facing: getFiles(userId: number, companyId: number) { this.fileService.getFiles(userId, companyId).subscribe(re ...

No response data being displayed after Angular post request

After sending a POST request via Postman, I received the expected response with a status of 400. However, when I tried sending the same request using Angular's http.post in the browser, I only received a 400 error without any response data. https://i ...

What is the process for personalizing the appearance in cdk drag and drop mode?

I have created a small list of characters that are draggable using Cdk Drag Drop. Everything is working well so far! Now, I want to customize the style of the draggable items. I came across .cdk-drag-preview class for styling, which also includes box-shado ...

What are the top techniques for designing with Angular 2 Material Design?

As a newcomer to angular 2 material design, I have noticed the primary, accent, and warn classes that apply specific colors to elements. Are these the only styling options available in Angular Material 2? Are there other classes that can be utilized for cu ...