ngModel fails to update value upon change

Having an ngModel within an ngFor loop:

<div *ngFor="let comment of comments">
   <div *ngFor="let answer of toArray(comment.answers); let j = index; trackBy: trackByIndex;">
      <textarea id="editAnswer[j]" name="editAnswer[j]" [(ngModel)]="answer.text">

      {{ answer.text }}
   </div>
</div>

In my component, I have implemented two functions to iterate through indices and convert objects into arrays:

  trackByIndex(index: number, obj: any): any {
    return index;
  }

  toArray(answers: object) {
    return Object.keys(answers).map(key => ({
      key,
      ...answers[key]
    }))
  }

The issue arises when the text bound in the textarea is changed, as the ngModel does not reflect these changes.

Here is a Stackblitz example: https://stackblitz.com/edit/angular-z6xatv

Answer №1

The method known as toArray is observed to be generating a duplicate set of the initial values found in comments.answers.text. Any modifications made to the text property within the input elements do not impact the original data (as evidenced by the console output in this stackblitz, where the values remain isolated).

If you streamline the implementation of toArray to simply return an array containing the answers, the code functions correctly (refer to this stackblitz). The elements in the array maintain shared references to the same text values present in the original dataset.

comments = [
  {
    text: 'dsddsdsd', answers: {
      FszW: { text: 'answer 1' },
      dsSce: { text: 'answer 2' }
    }
  }
]

toArray(answers: object) {
  return Object.keys(answers).map(key => answers[key]);
}

If access to the keys is required, this updated version of toArray can be utilized:

toArray(answers: object) {
  return Object.keys(answers).map(key => {
    return { key: key, value: answers[key] };
  });
}

Incorporate the subsequent template structure:

<textarea name="answer_{{j}}" [(ngModel)]="answer.value.text"></textarea>
{{ answer.key }}: {{ answer.value.text }}

Besides, it's recommended to assign the name property in the template using one of these formats:

name="answer_{{j}}"
[name]="'answer_' + j"

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 appearance of a slide-in hamburger menu causes the horizontal scrollbar to appear

To create a hamburger menu that slides in from the right when clicking the icon, follow this code snippet. Here is the main menu code where it is initially translated to the right by 100% and on icon click, it comes back on screen with a translation of 0% ...

Ways to properly assign a key in a Generic Interface as the interface key

Can someone assist me with TypeScript generics? I am wondering how to access the T["value"] field within the ActionAdd interface. type UserValue = { username: string; }; interface User { id: number; value: UserValue; } interface ActionAdd<T = unkn ...

What is the best way to link function calls together dynamically using RXJS?

I am seeking a way to store the result of an initial request and then retrieve that stored value for subsequent requests. Currently, I am utilizing promises and chaining them to achieve this functionality. While my current solution works fine, I am interes ...

Is it advisable to utilize TypeScript interfaces for declaration files and React component prop definitions?

Whenever I create structures for object types, my go-to method is to define them in my declaration.d.ts file like this: type TagsObject = { _id: string; tag: string; } type ProjectData = { _createdAt: string; _id: string; _rev: string; _type: ...

Having difficulties establishing a connection with the websocket URL generated by Spark Java

I'm currently working on creating a websocket using the sparkjava framework. Here is the code snippet for setting up the websocket: public final class MainWS { static Map<Session, String> USER_SESSION_MAP = new ConcurrentHashMap<>(); stat ...

Is a package.json file missing dependencies?

Curious about the meaning of peerDependencies, I examined the contents of this package.json file. It relates to a library project that is distributed elsewhere. { "name": "...", "version": "...", "description": "...", "author": "...", ...

A guide to leveraging React.lazy within your Gatsby projects

When attempting to use React.lazy in Gatsby for production by running gatsby build, errors may arise. What would be the most effective approach to implement React.lazy and suspense in a Gatsby Project? ...

Alert: warning:0308010C:digital envelope routines::unsupported [ANGULAR]

I've encountered an issue while trying to build my project on Jenkins. The local build is successful, but the Jenkins build keeps failing. Does anyone know how to fix this? I am using the primeng module to implement p-organisationchart, and I suspect ...

Creating a dynamic text design using Bootstrap or CSS: What's the best approach?

I attempted to enable responsive font sizes in Bootstrap 4.3.1 by setting the $enable-responsive-font-sizes variable to true, but I did not see any changes. Below is the code from my template.html file: <div class="m-2" id="role" ...

What causes compilation errors while attempting to integrate Angular elements into a Material Dialog component?

I attempted to set up a basic Angular application with a Material Dialog, but encountered difficulties when trying to include any Angular-specific elements in the HTML of the dialog (such as using <mat-dialog-content> or [(ngInput)]), resulting in co ...

Is it possible to bind the Polymer paper-dropdown-menu with ngControl in Angular?

I'm currently working on building a form in Angular2 using the Polymer paper-dropdown-menu element. I've been struggling to figure out how to bind the selected value of the dropdown to my component's control. Despite numerous attempts, I hav ...

Implement validation within the child component using Reactive Forms

In this demonstration, a reactive form has been created with an input field placed inside a child component. The goal is to add a new form control within the child component and perform validation on it within the same component. However, an error has been ...

What steps should I take to deploy my Node.js (using TypeScript) backend on Vercel?

After meticulously designing the backend of my MERN application using TypeScript and configuring it to perfection, here is the hierarchy of my project: https://i.sstatic.net/DdOkqEe4.png Here's a glimpse of my tsconfig.json. { "compilerOptions": { ...

Encountering a dependency tree error while attempting to execute the command "npm i @angular/cdk."

I attempted to execute the following command npm i @angular/cdk Unfortunately, I encountered this error : npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-protection ...

When attempting to display the image file path using the JavaScript API Notification in Angular, there is a challenge in

Hello fellow developers, I am currently facing an issue with retrieving a local image from my assets folder and displaying it on a new Notification object generated by the Web Notification API. I have an image in my assets folder with a .jpeg extension. ...

A guide to representing a TypeScript interface as a UML model

As I work on designing a class diagram for an Angular application, I come across the need to understand how TypeScript is utilized in such projects. It's worth noting that Angular apps are primarily written in TypeScript. Within TypeScript, one inter ...

Retrieve the radio button value without using a key when submitting a form in JSON

Looking to extract the value upon form submission in Angular, here is the code: In my Typescript: constructor(public navCtrl: NavController, public navParams: NavParams, public modalCtrl: ModalController, public formBuilder: FormBuilder, public alertCtrl ...

Discovering the dimensions of a video in Angular 2 using TypeScript

To determine whether the video is portrait or landscape, I am attempting to retrieve the height and width of the video using the following method: import { Component, OnInit, AfterViewInit } from '@angular/core'; @Component({ selector: ' ...

Guide to employing Axios types in project declaration files

When working on my project's type declaration file, I encountered a dilemma with using Axios types as part of my own types. The issue lies in the fact that all declarations for Axios are exported from their official repository. I specifically need to ...

Encountering the error message `[Vue warn]: The component failed to mount: template or render function not defined` occurs when attempting to import a file without the .vue extension

I'm facing an issue where I am unable to import components from a Vue file without having to append the .vue extension. In my project, which is a Vue project with TypeScript and a class-based setup, I have separated the script and template files (.ts ...