Create a feature in Angular that allows for the dynamic addition of input fields that are connected to a generic

I am dealing with a standard key value array

cost: {[ key: string ] : number};

I am exploring ways to configure a dynamic input field

<input name="costCat" [(ngModel)] = "???"/>
<input name="costVal" [(ngModel)] = "???"/>

that can be increased automatically using a button based on the number of cost categories.

The objective is to achieve an object like this:

'{"everyone":"10"}'

or even something similar to this

'{"young":"free", "adult":10, "elderly":"free"}'

Answer №1

After working on it for some time, I finally came up with this solution:

Here is what the ts file looks like:

export class AppComponent implements OnInit {
  name = 'Dynamic Add Fields';
  values = [];
  ngOnInit() {
  }

  removevalue(i){
    this.values.splice(i,1);
  }
  
  addvalue(k:string){
    this.values.push({key:k,value: ""});
  }
  
}

And here is the html file implementation:

<div *ngFor="let value of values; let i = index"> 
  <input type="text" [(ngModel)]="value.key" #name="ngModel" name="value{{i}}">
  <input type="text" [(ngModel)]="value.value" #name="ngModel" name="value{{i}}">
  <button (click)="removevalue(i)">Remove</button>
</div>
<button (click)="addvalue('')">ADD</button>


<h2>Result</h2>
<div *ngFor="let value of values;">
  {{ value.key }}:{{value.value}}
</div>

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 correct way to apply type in the .call() method?

I need help finding a solution for the following issue interface IName { name:string; } let obj1:IName = { name: "LINUS" } function profileInfo (age:number,location:string):string{ return `${this.name} is ${age} years old and is from ${location ...

Event triggered by clicking on certain coordinates

Just starting with @asymmetrik/ngx-leaflet and Angular, so this might be a beginner's issue... I'm working on an Angular.io (v5) project that incorporates the @asymmetrik/ngx-leaflet-tutorial-ngcli Currently, I'm trying to retrieve the coo ...

Waiting for the HTTP Post response in Angular 2

My Angular2 app is written in TypeScript. I encounter an issue when making a HTTP Post request to create a new record, as the return value from the service does not come back in time to update the DOM with the newly created record. Is there a way to pause ...

Contrasting expressEngine and ng2engine: An In-depth Comparison

I am currently utilizing the universal-starter framework. In regards to the file server.ts, I noticed that making the switch from import { expressEngine } from 'angular2-universal'; app.engine('.html', expressEngine); to import { n ...

Tips for building a calculated field within Angular's reactive forms

I have recently implemented a form in my application and here is the code snippet: mapForm = this.fb.group({ name: ['', Validators.required], view: this.fb.group({ width: ['', Validators.required], height: [' ...

Which ngTagsInput version is recommended for Angular instead of AngularJs?

After discovering the ngTagsInput framework on this site, I found it to be a very comprehensive library. However, for Angular 8 users like myself, I came across the ngx-chips framework on this page. While ngx-chips seems to work, I noticed that it lacks s ...

Guide to activating data transfer object validators in NEST JS

I have recently started using NEST JS and I am currently working on implementing validators in DTO's. This is what my code looks like: // /blog-backend/src/blog/dto/create-post.dto.ts import { IsEmail, IsNotEmpty, IsDefined } from 'class-validat ...

Displaying an array object within an array of objects in Angular 2: A guide

Here is an example of a JSON file: { "id": 5, "url": "http://localhost:8000/api/v1/users/5/", "username": "Najmuddin", "email": "", "groups": [ { "id": 1, "url ": "http://localhost:8000/api/v1/groups/1/", ...

Tips for RETRIEVING a particular cookie value in Angular version 14

"I've integrated the ngx-cookie-service library in my Angular project, but I'm experiencing an issue where two different cookies are being retrieved upon login even though the session id is already set in the backend. How can I ensure that m ...

The 'style' property is not found within the 'EventTarget' type

Currently, I am utilizing Vue and TypeScript in an attempt to adjust the style of an element. let changeStyle = (event: MouseEvent) => { if (event.target) { event.target.style.opacity = 1; Although the code is functional, TypeScript consist ...

`Drizzle ORM and its versatile approach to SELECT statements`

Looking to improve the handling of options in a function that queries a database using Drizzle ORM. Currently, the function accepts options like enabled and limit, with potential for more options in the future. Here's the current implementation: type ...

core.mjs:6484 ALERT There was an issue with reading the 'name' property as it was undefined

I'm encountering an error message in the console.log that I can't seem to resolve... Here is the error message: core.mjs:6484 ERROR TypeError: Cannot read properties of undefined (reading 'name') https://i.stack.imgur.com/tlun6.png H ...

Struggling with verifying the visibility of multiple elements using the toBeVisible() assertion

While running a test in debug mode, I've observed that toBeVisible() fails when it detects multiple elements. Interestingly, toBeVisible without the parenthesis passes the assertion in such cases. I'm facing a specific scenario where I need to p ...

Experiencing difficulty retrieving individual :id information from a list in MEAN stack

**I'm experiencing issues retrieving a single :id from a list as the data returned is not what I expected... ** GET /article/5b0be8829f734a4e580a43c5 401 3.845 ms - 99 ===> response from my get request my api ===> var express = require ...

The specified "ID" type variable "$userId" is being utilized in a positional context that is anticipating a "non-null ID" type

When attempting to execute a GraphQL request using the npm package graphql-request, I am exploring the use of template literals. async getCandidate(userId: number) { const query = gql` query($userId: ID){ candidate( ...

Bringing in a TypeScript module to an Angular component

Having trouble with including a specific library in my component Here is the code for my component which uses geolib as the library: import { Component, OnInit } from '@angular/core'; import { StationsService } from '../../../services/stati ...

Effortlessly passing props between components using React TypeScript 16.8 with the help

In this scenario, the component is loaded as one of the routes. I have defined the type of companyName as a string within the AppProps type and then specified the type to the component using <AppProps>. Later on, I used {companyName} in the HTML rend ...

The interactive Material UI Radio buttons are not responding to click events due to dynamic generation

Click here to see the demo in action: https://codesandbox.io/s/material-demo-9fwlz I expected this code to produce checkable radio elements, but it doesn't seem to be working correctly. Can anyone identify what might be causing the issue? This code s ...

What is the best way to search through string enums in TypeScript strict mode?

Implementing TypeScript 2.8.4 in strict mode Here's an enum example: export enum TabIndex { Editor = 'editor', Console = 'console', Settings = 'settings', Outputs = 'outputs' } I am creating a Map fro ...

Exploring Angular 5 testing: Strategies for simulating an HTTP error in mocks

Currently, I am working on testing a unit in Angular 5. While I am familiar with using the flush method in HttpTestingController to mock response data with the new http module, I am unsure about how to mock an error (as I need to test my error handler). A ...