The issue with Angular's two-way data binding in a string array is that it is not functioning properly

Can someone help me understand the correct way to use ng-model in an array of strings?

I attempted the following:

Component.ts

toDos: string[] =["Todo1","Todo2","Todo3"];

Component.html

<div *ngFor="let item of toDos;let index = index">
   <input [(ngModel)]="toDos[index]" placeholder="item" name="word{{index}}">
</div>

Although this code does not show any errors, it doesn't update the input contents correctly. Can anyone provide guidance on the correct approach?

You can see the issue in action on this StackBlitz example when attempting to edit an input field: StackBlitz

I would appreciate any help or suggestions on how to resolve this problem. Thank you!

Answer №1

To keep track of the length of the to-dos list, you can create an auxiliary array called 'count' with the same length as the to-dos list.

toDos: string[] =["Todo1","Todo2","Todo3"];
count:number[]=new Array(this.toDos.length); //An auxiliary array
click(){
   this.toDos.push("Todo4");
   //if the length of the to-dos array changes, we need to update the count array as well
   this.count=new Array(this.toDos.length)
}

<!--we loop through the count array-->
<div *ngFor="let item of count;let index = index">
   <input [(ngModel)]="toDos[index]" placeholder="item" name="word{{index}}">
</div>

Answer №3

To access the value in the for loop, you can utilize the item directly within the loop

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

React Typescript: The specified argument type cannot be assigned to the parameter type

Creating a Check Box Button React component has resulted in an error related to setRSelected(1) and setRSelected(2)... const [cSelected, setCSelected] = useState([]); const [rSelected, setRSelected] = useState(); const onCheckboxBtnClick = (selected ...

Information is failing to upload to the Firebase database

I have encountered an issue while trying to push data to Firebase. The data does not appear in the Firebase console, even after installing all necessary npms. I have attached all the relevant files for reference. Service file: import { Injectable } from ...

Unable to retrieve this information within an anonymous function

I am currently working on converting the JSON data received from an API interface into separate arrays containing specific objects. The object type is specified as a variable in the interface. Here is the interface structure: export interface Interface{ ...

How can I retrieve data during a double-click event in Kendo Grid using Angular?

How can I retrieve data on the doubleClick event in a Kendo Grid? I want to access the same object that is fetched during the selected event, which would be the dataitem at the selected index row. HTML: <kendo-grid #myGrid [data]="gridDat ...

Passing additional parameters to an Angular directive individually

Is there a way to pass two parameters separately to my directive instead of as one combined parameter? Currently, I am able to add the parameters as one parameter (*ovLoading="!isDataReceived;noBackground:true"), but I would prefer to have them as two sepa ...

Collision Detection in Kendo UI Menu

When working with TypeScript, it ensures that the parameters are of the correct type. For Kendo's menu, in order to disable the popupCollision property, you need to set it to false. However, this property actually accepts a string as its value, so if ...

Struggling to locate root directory post-Angular 13 upgrade in Jest

After updating my project to Angular 13, I realized that Jest required some adjustments as well. Now, any mention of 'src' cannot be resolved properly. For instance: Cannot find module 'src/app/app.component/app.component.test' from & ...

Angular ngFor Directive Failing to Display Menu Item Information on Right-Click Context Menu

Currently encountering an issue with implementing a right-click function in my context menu. The menu items are not appearing due to the second ngFor="let row" condition... however, I require the selected row object from a right click to pass in a JSON val ...

Encountering the error message 'Object is of type unknown' when implementing the createAsyncThunk function post utilization of Typescript and Redux Toolkit

Currently, I am utilizing Typescript in my React application where Redux Toolkit is being used for state management. The data is being fetched from an Express Api and everything operates smoothly if Redux is implemented without Typescript. However, when in ...

Tips for looping through an array of objects in Angular 9 and adjusting the time if the <mat-checkbox> is selected

I am currently working with an array of objects that are displayed in a <mat-table>. Each object has a property called sync, which is represented by a <mat-checkbox>. My goal is to create functionality where checking the box and then pressing ...

Discovering the best approach to utilizing Font Awesome 6 with React

Required Packages "@fortawesome/fontawesome-svg-core": "^6.1.1", "@fortawesome/free-solid-svg-icons": "^6.1.1", "@fortawesome/react-fontawesome": "^0.1.18", "next": " ...

TypeScript functions with Generic Constraints return specific values rather than just types

function createGenericCoordinates<Type extends number | string>( x: Type, y: Type ) { return { x, y }; } const genericCoordinates = createGenericCoordinates(1, 2); // Error (TS2322) // Type 3 is not assignable to type 1 | 2 genericCoordinates ...

Tips for sending back a response after a request (post | get) is made:

In the service, there is a variable that verifies if the user is authorized: get IsAuthorized():any{ return this.apiService.SendComand("GetFirstKassir"); } The SendCommand method is used to send requests (either as a post or get request): ApiServi ...

When you use Array.push, it creates a copy that duplicates all nested elements,

Situation Currently, I am developing a web application using Typescript/Angular2 RC1. In my project, I have two classes - Class1 and Class2. Class1 is an Angular2 service with a variable myVar = [obj1, obj2, obj3]. On the other hand, Class2 is an Angular2 ...

Utilizing Angular to nest a simple component within another component and display it exclusively on a targeted page or parent component

Currently, I am developing a mobile app using Ionic 3 and have created 2 components - Dumb or presentation components. The first component is the <ion-navbar>, which contains another component called <header-wallet-badge></header-wallet-badg ...

Use RxJS to ensure one observable waits for another observable to emit a non-null value

I am currently facing an issue with my setter function in TypeScript. In this setter, I assign a class member observable called systemAreasOptions$. The reason behind doing this in the setter is because it needs to wait for the observable mappedItem$ to ...

Using Angular with Bootstrap to implement a typeahead feature

I've been working on getting my Typeahead feature to function properly: <div *ngFor="let item of items; index as i"> <input type="text" name="name{{i}}" [(ngModel)]="item.name" [ngbTypeahead]="searchItem" /> </div> Within the c ...

Issues with showing data in Angular Material tables

I recently deployed my Angular Application on a server and encountered an issue with the Angular Material table. Despite data being present in the logs, it does not display on the table. This problem only occurs in production, as everything works perfectl ...

Tips for ensuring a program pauses until an observable is completed within an Angular application

Currently, I am working on a project using Angular. I encountered a situation where a call to the backend is made using an observable to fetch products. Below is an example of how the code appears: getProducts () : Product[] { this.http.get<[]>(this ...

The incorrect child output is causing the observable to trigger erroneously, resulting in the observable receiving inaccurate

For quite some time now, I've been struggling to identify the issue in my code. The scenario is that I have a child component acting as a modal, which includes a search bar. When the user interacts with the search bar, it triggers an event to the pare ...