How can I increase the number of input boxes dynamically when clicking a button?

I am currently working on developing a checklist application, and I'm facing a challenge with the functionality. The user should be able to add items by clicking a button which opens input boxes for item name and quantity. While this initial part works fine, I'm struggling to make it so that when the user wants to add another item, more input boxes are dynamically generated. I am using Angular and typescript without utilizing $scope.

Below is my controller:

   export class CreateItemListController {
        public itemList;
        public item;
        public items = [];

        public addNew() {
            debugger;
            this.items = []
            var item = {itemName: "default name", itemQty: "default qty"}; // you can set default values here
            this.items.push(item);
        }

HTML:

<form>
    <div>
   Title <input ng-model="controller.itemList.title" />

    <div ng-repeat="item in controller.items">
        Item Name <input ng-model="controller.item.itemName" />
        Quantity <input ng-model="controller.item.itemQty" />
    </div>
    <button ng-click="controller.addNew()">Add New Item</button>
</div>
       <button ng-click="controller.save()" type="submit">Submit</button>
</form>

Models:

namespace BringIt.Models {
    public class ItemList {
        public int Id { get; set; }
        public string Title { get; set; }
        public DateTime EventDate { get; set; }
        public ICollection<Item> Items { get; set; }
    }
}


namespace BringIt.Models {
    public class Item {
        public int Id { get; set; }
        public string ItemName { get; set; }
        public int ItemQty { get; set; }
        public string Person { get; set; }
        public ItemList ItemList { get; set; }
    }
}

Answer №1

It seems like the issue may be stemming from constantly re-initializing your array within the addNew() function. Try modifying the function to

public addNew() {
        var item = {itemName: "default name", itemQty: "default qty"};
        this.items.push(item);
    }

Note that I have eliminated the this.items = [] line

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

I must display the output in the proper format as illustrated below

angular.forEach(caseChangeRecord, function(change, key) { if (caseChangeRecord != 'undefined') { body += change.fieldName + ' : ' + change.newValue; } }); Expected Display Output: A:B A:B A:B ...

Top method for alerting a directive within a Collapsible directive about a collapse occurrence in AngularJS

Seeking advice on the best method for a container to communicate with a contained element concerning changes in collapse status. The situation involves a custom collapsible directive with isolated scopes, as well as other directives within it that also hav ...

Angular: directive modifying the value of a form control

I have implemented a feature to automatically transform the slug when the user inputs the name in a control field. This transformation includes changing spaces to hyphens (-) among other things. Although I created a directive for this purpose, it seems to ...

"Encountered an error: 'Invalid private class xy' in the process of constructing an Angular library

Currently, I am in the process of creating an npm package using Angular. In the midst of building the library, I encountered the following error: An unexpected issue with the private class MyLibComponent has surfaced. While this class is accessible to us ...

Issue with the Angular directives

Encountered an issue while trying to instantiate module store: Error: [$injector:nomod] http://errors.angularjs.org/1.3.9/$injector/nomod?p0=store) (A more descriptive error) The 'store' module is not accessible! Please double-check the spellin ...

Web design that adapts to different screen sizes and the ability to

As a beginner in both responsive web design and Angular, I am currently working on creating a webpage that will retrieve data from a SQL Server table to display on the site. Can anyone suggest how I can access this data from the database? Would I require ...

How to use AngularJS to showcase intricate data structures

Here is the JSON data that I have: { "_id": "543e95d78a1cec2a38ed53ec", "result": { "CAR009": [ { "name": "BMW" }, { "name": "MERCEDES" } ], "BUS007": [ { ...

Troubleshooting Problem with HTTP Requests in Angular 2 on Firefox Browser

I have encountered a peculiar issue with my Angular 2 application specifically on Firefox and all iOS browsers (Firefox, Safari). Whenever a user navigates to the /reports route in my application, I am making a REST API call using the ngOnInit method to f ...

Django error: The 'Campaign' does not contain the 'ads' attribute

I've been attempting to set up a nested serializer in Django Rest Framework, however I keep encountering this error. I understand the reason behind it, but I assumed Django would handle the one-to-many relationship for me. AttributeError at /api/ca ...

Angular Karma test event capturing e.currentTarget opportunity

I've been putting in a lot of hours trying to make this work. I'm attempting to test a $scope.function that triggers an API call based on target = e.currentTarget and input.val(), but I'm currently at a standstill. My question is, how can I ...

Error: [$injector:unpr] Oh no! The AuthServiceProvider Angular Service seems to be MIA

I am currently working on a small AngularJS project and encountering an issue with my service files not being successfully injected into the controllers. I have double-checked for any syntax errors, but despite trying different variations, the problem pers ...

Utilize AngularJS to loop through a list with ng-repeat

Seeking guidance as an Angular newbie. The ng-repeat in question is formatted as: ng-repeat="f in drillDownList['D' + d.merchMetrics.DEPT_NBR + 'CG' + d.merchMetrics.CATG_GRP_NBR + 'C' + d.merchMetrics.DEPT_CATG_NBR] M ...

The NodeJS namespace does not include the exported member "Global." It is recommended to replace NodeJS.Global with typeof globalThis

Can you show the proper way to utilize typeof globalThis? Please provide a detailed explanation, without taking any shortcuts. interface CustomNodeJsGlobal extends NodeJS.Global { foo: { bar: string | null } } Upon execution, you may encounter the ...

Learning to handle data fetching and looping in NextJs

I'm facing an issue with fetching data through a loop in getStaticProps. The array ends up empty due to asynchronous code. If I pass the ID array and implement the logic within the React component, it works fine. Should I continue using the component ...

Is there a way to retrieve a comprehensive list of all anchors that contain the data-ng-click attribute

I am currently working on a web application built with asp.net and angularjs. My goal is to specifically retrieve all anchor tags that have the attribute data-ng-click assigned to them. Is there a way to achieve this? If so, how can it be done? I a ...

Utilizing an AwsCustomResource in AWS CDK to access JSON values from a parameter store

I found a solution on Stack Overflow to access configurations stored in an AWS parameter. The implementation involves using the code snippet below: export class SSMParameterReader extends AwsCustomResource { constructor(scope: Construct, name: string, pr ...

Evaluate the functionality of an Angular controller method that interacts with the Document Object Model (

We currently have an AngularJS controller that contains the following function: $scope.testMe = function() { return $('#test'); } So, how can we effectively test this function? We attempted a Karma test as shown below: describe(' ...

Struggling to implement a vertical scroll bar in HTML code?

<body ng-app="myApp" ng-controller="myCtrl"> <div ng-show = "dataFromRest" ng-repeat = "x in dataFromRest.posts" > <div class="tittle" style="width: 25%;"> <a href="" ng-click="showDi ...

Best practice for importing ts files from an npm package

When faced with the need to divide a ts project into multiple repositories/packages for creating microservices, the challenge arises in combining these packages efficiently. Some packages are required in one microservice, others in another, and some in all ...

Consolidate multiple generic items into a single entry

In my current project, I am structuring the types for a complex javascript module. One of the requirements is to handle multiple types using generics, as shown in the snippet below: export interface ModelState< FetchListPayload, FetchListR ...