Exploring Angular 8: Connecting elements to an array filled with objects

My goal is to achieve the following:

https://i.sstatic.net/TQeKN.png

In my form, I have 2 fields: description and price. When the plus button is clicked, additional input fields (Input 2 and Price 2) are generated dynamically. I want to bind these fields to an array of objects.

additionsOfProductArray: Array<NewProductAddition>=[];
class NewProductAddition{

  additionDescription:string;
  additionPrice:number;
}

This is what I've tried that's not working:

<div class="row mt-5"
        *ngFor="let currentNumber of numberOfTimesAdditionArray | slice:0:numberOfTimesAdditions;let i = index">
        <div class="col-8">
          <input type="text" class="form-control" name="additionDescription" placeholder="Enter Description"
            [(ngModel)]="additionsOfProductArray[i].additionDescription">
        </div>
        <div class="col-4 ">
          <div class=" ml-5 input-group-prepend">
            <span class="input-group-text">€</span>
            <input type="number" class="form-control col-xs-3 priceinput" min="1" step="any"  name="articlePrice"
              [(ngModel)]="additionsOfProductArray[i].additionPrice">
            <span class="input-group-text">.00</span>
          </div>
        </div>
      </div>

Button Click

<div class="col-2">
          <button (click)="increaseTheAdditionNumber()">
            <span class="glyphicon glyphicon-plus"></span>
          </button>
        </div>


  increaseTheAdditionNumber(){
    this.numberOfTimesAdditionArray=[];
    this.numberOfTimesAdditionArray= [...Array(++this.numberOfTimesAdditions).keys()] ;
  }


 numberOfTimesAdditionArray=[...Array(this.numberOfTimesAdditions).keys()];
  numberOfTimesAdditions=1;

Any help or suggestions would be greatly appreciated.

Answer №1

Kindly attempt to utilize this instance

within the template

<div class="row mt-5"
        *ngFor="let product of additionsOfProductArray; let i = index">
        <div class="col-8">
          <input type="text" class="form-control" name="additionDescription" placeholder="Enter Selection Description"
            [(ngModel)]="product.additionDescription"></div>
        <div class="col-4 ">
          <div class=" ml-5 input-group-prepend">
            <span class="input-group-text">€</span>
            <input type="number" class="form-control col-xs-3 priceinput" min="1" step="any"  name="articlePrice"
              [(ngModel)]="product.additionPrice">
            <span class="input-group-text">.00</span>
          </div>
        </div>
      </div>

within the TypeScript file

increaseTheAdditionNumber(){
    this.additionsOfProductArray.unshift(new NewProductAddition());
    // or use the example below if you prefer
    // this.additionsOfProductArray.push(new NewProductAddition());
}

I noticed in the comments that you are hesitating to add elements into your additionsOfProductArray array. Could you please elaborate on the reason? Perhaps we can explore alternative solutions involving the addition of elements to the additionsOfProductArray.

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 NullInjector has issued an error regarding the lack of a provider for the Decimal

I recently integrated lazy loading into my application. However, one of my services is in need of the DecimalPipe. The structure of my modules goes like this: service -> shared module -> App module To give you more context, I have already added "Co ...

Is there a way to modify the antd TimePicker to display hours from 00 to 99 instead of the usual 00 to 23 range?

import React, { useState } from "react"; import "./index.css"; import { TimePicker } from "antd"; import type { Dayjs } from "dayjs"; const format = "HH:mm"; const Clock: React.FC = () =& ...

Bringing in a module that enhances a class

While scouring for a method to rotate markers using leaflet.js, I stumbled upon the module leaflet-rotatedmarker. After installing it via npm, I find myself at a loss on how to actually implement it. According to the readme, it simply extends the existing ...

Confirm the Keycloak token by checking it against two separate URLs

In my system, I have a setup based on Docker compose with back-end and front-end components. The back-end is developed using Python Flask and runs in multiple docker containers, while the front-end is coded in TypeScript with Angular. Communication between ...

What is the method for retrieving interface key types in TypeScript?

My question relates to an interface. interface Some { key1: string key2: number } I am working with a function. const fn = (key: keyof Some) => { return <Some>someObject[key] } Is it possible to determine the return type based on a string ...

Exploring type definition for function arguments in TypeScript and React

There is a high-order component (HOC) designed to store the value of one state for all input and select elements. The output function accepts arguments ({text: Component, select: Component}). An error is displayed while typing an argument: TS2322: Type &ap ...

Performing calculations on two properties of an observable object in Angular 8 and then storing the result in a new property

Looking for guidance on how to display the sum of two properties from an observable data. Take a look at the code below and let me know your thoughts: Typescript class export class Amount { Amount1: number; Amount2: number; Total:number; } In typescript ...

"Unsuccessful API request leads to empty ngFor loop due to ngIf condition not being

I have been struggling to display the fetched data in my Angular 6 project. I have tried using ngIf and ngFor but nothing seems to work. My goal is to show data from movies on the HTML page, but for some reason, the data appears to be empty. Despite tryin ...

Angular: Material Button that Adjusts According to Header Size

How can I adjust the size of a mat-icon to match the header size? Despite my efforts, the arrows remain small. <h1> <button mat-icon-button (click)="testEvent()"> <mat-icon>keyboard_arrow_up</mat-icon> < ...

Troubleshooting problem with refreshing URL on "ionic serve" mode

After transitioning my project from Ionic 2 to Ionic 3, I've encountered an issue with ionic serve and the rebuilding process. Initially, when I build the project, everything functions as expected. However, I've noticed that the URL in the brows ...

Encountering 'npm install' error while trying to follow the Angular2 5 minute

I encountered an error while attempting to follow the Angular2 5 min quick start guide. Can someone assist me in resolving it? vagrant@vagrant-ubuntu-trusty-64:/vagrant/angular2-tutorial$ sudo npm install <a href="/cdn-cgi/l/email-protection" class=" ...

How come this mocha test is exceeding its timeout limit when making a basic call with mongoose?

Trying to write a simple assertion for an asynchronous database method: describe('User Repository', () => { describe('findById', () => { it('Returns a user that can be found in the database by ID', async () => { ...

The current Angular CLI version is displayed as 7.3.9, not version 8

I am currently working on setting up a new Angular project using the latest version of Angular. After installing the Angular CLI globally with the command npm install -g @angular/cli, I ran ng v to check the version and it displayed Angular CLI: 7.3.3 in ...

When the button is clicked, a fresh row will be added to the table and filled with data

In my table, I display the Article Number and Description of werbedata. After populating all the data in the table, I want to add a new article and description. When I click on 'add', that row should remain unchanged with blank fields added below ...

Google's reCAPTCHA issue: systemjs not found

Currently, I am attempting to integrate Google's reCAPTCHA into an Angular application by following a helpful tutorial found here. However, I have encountered a problem as the systemjs.config.js file seems to be missing from my Angular CLI project. An ...

How to handle multiple formData input in NestJS controller

How can I create a controller in Nest.js that accepts two form-data inputs? Here is my Angular service code: public importSchema(file: File, importConfig: PreviewImportConfig): Observable<HttpEvent<SchemaParseResponse>> { const formData = ...

The Angular 6 test command using npm has encountered a failure

I've been encountering a disconnect error while attempting to run Angular test cases. With over 1500 test cases written, it appears that the sheer volume may be causing this issue. Is there a way to resolve the disconnect error when running such a lar ...

Oops! The type '{}' is lacking the properties listed below

interface Human { firstName: string; lastName: string; } let human1: Human = {}; human1.firstName = "John" human1.lastName = "Doe" Upon declaring human1, an error pops up: Type '{}' is missing the following properties from type Human ...

"The list of table rows in a React application using Typescript is not rendering properly

I am encountering an issue where the rows in my table are not being rendered while trying to map objects from a list called items. I am working with typescript and react-bootstrap. Can someone help me understand why this is happening and how to resolve it? ...

Using the "Range" Input Type in Angular's Reactive Forms

I'm having difficulties with styling the background of my slider/range in reactive forms within Angular. The input value updates correctly, but the issue arises when I try to type in the input field - the range changes, but the color (green) remains s ...