Link JSON object array to a form by utilizing ngModel in Angular2

My current challenge involves creating a form for a "question" object, which consists of an array of strings for answers. I am struggling to bind these answers to the question model.

An initial implementation might look like this:

import { Component  } from '@angular/core';
class Question {
  question: string;
  answers: Array<string>;
}

@Component({
  selector: 'app',
  template: `
<input type="text" [(ngModel)]="question.question">
<input type="text" *ngFor="let answer of question.answers" [(ngModel)]="answer">
`
})

export class AppComponent {
  question: Question = new Question;
  question.answers = new Array(4);
  constructor(){};
}

The issue arises with the second ngModel. This solution triggers the error:

zone.js:388 Unhandled Promise rejection: Cannot assign to a reference or variable! ; Zone: <root> ; Task: Promise.then ; Value: Error: Cannot assign to a reference or variable!

It appears that binding a generated value from an ngFor loop to a model is not possible.

I have also experimented with other options:

  • [(ngModel)]="question.answers[index]"
    -> Here, I used let index=index; within ngFor and assigned a name to the input. However, this resulted in the same error mentioned in the following paragraph
  • [(ngModel)]="question.answers[] -> Attempting a similar approach as using pure HTML, but this method did not work at all

None of these attempts yielded the desired outcome. When changing a value in an input field, it seemed to refresh the ngFor loop. Additionally, when I tried to allow users to append or delete an answer, adding a new answer would erase the content of the first one.

Answer №1

If I were to suggest, you have a couple of choices:

1 Consider Using an Object Instead of an Array

You could go through the object using ngFor and a pipe as detailed in this Stack Overflow post on Iterating over TypeScript Dictionary in Angular 2

@Pipe({ name: 'values',  pure: false })
export class ValuesPipe implements PipeTransform {
  transform(value: any, args: any[] = null): any {
    return Object.keys(value).map(key => value[key]);
  }
}

<div *ngFor="#value of object | values"> </div>

2 Utilize a Separate Array for the ngFor Loop, similar to what's shown in this example on Plunker

import { Component } from '@angular/core';

export class Hero {
  id: number;
  name: string;
}

@Component({
  selector: 'my-app',
  template: `<h1>Hello {{name}}</h1>
  <div *ngFor="let count of dummyArr; let i=index">
     <input type="number" [(ngModel)]="data[i]">
  </div>
  `
})
export class AppComponent implements OnInit { 
  name = 'Angular';
  data:number[]=[];
  dummyArr:number[]=[];

  ngOnInit(){
    this.data.length=6;
    this.dummyArr.length=6;
  }
}

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

Combine a string and integer in JavaScript without using quotation marks between them

Is there a way to concatenate a string and an integer in JavaScript without getting the ": Here is the code snippet: "<agm-map latitude=" + response.latitude + " longitude=" + response.longitude + "></agm-map>"; What it currently results in: ...

Refresh Angular component upon navigation

I have set up routes for my module: const routes: Routes = [ { path: ":level1/:level2/:level3", component: CategoriesComponent }, { path: ":level1/:level2", component: CategoriesComponent}, { path: ":level1", component: ...

Using PostGraphile's NodeId identifiers for composite PrimaryKeys

We integrated a Postgraphile mutation plugin using the method makeExtendSchemaPlugin. Within our plugin, we utilize the NodeId and parse it using the method getTypeAndIdentifiersFromNodeId. This function returns the GraphQL Type and a collection of Identi ...

How to send a value to a function in Angular from a different function?

Within my Angular Typescript file, I am working with two functions named data and lists. My goal is to pass the variable windows from the function data to the function lists. However, when attempting to call the function lists, I encounter an error: Canno ...

Testing the receiveMessage function in SQS using Jest unit tests

Struggling to find the right approach for unit testing this function. I almost have it, but can't quite nail it down. Take a look at the function below: receiveMessage(callback: Function): any { this.sqs.receiveMessage( this.params, ...

Deploying an Angular application on Firebase is a great way to

I am facing an issue with hosting my Angular(5) project on Firebase. Although I have successfully deployed the application, when I access the project URL, it displays a default Firebase hosting screen instead of my actual Angular project. https://i.stack. ...

What is the method to empty input fields after data has been submitted in an Angular application?

    I'm facing a challenge with my web form. I have a dropdown menu using mat-select and an input field. When I click the submit button, the data is sent. However, I want the input field to clear after submission without affecting the mat-select dr ...

Is it possible to selectively exclude features such as routes and components from my Angular application during the build process based on the environment configuration file?

I am interested in creating two variations of my Application using the same codebase. One version will have the "registration" feature included, while the other will not. Is there a way to configure Angular so that an environment file dictates what is ex ...

How can I display validation errors when submitting a form with ngx-materialize?

The page at demonstrates examples where the submit button is disabled until the form is valid. I am interested in enabling the submit button and displaying validation errors upon submission if there are any. Is this achievable? ...

Encountering an issue when attempting to import a non-source module from a node library while running a Typescript script

I have a script that takes input and utilizes the three.js library to apply geometric transformations to the data. I execute this script using ts-node pipeline.ts. Here is the structure of my project: ├── package-lock.json ├── package.json ├ ...

Retrieve data from TypeScript file (.ts) and use it in an HTML document

Recently I started learning Typescript and HTML as I work on building an Angular2 application. At the moment, I have a TypeScript file that resembles the following structure: import {Http, Headers} from 'angular2/http'; import {Component} from & ...

Is it necessary to compile the ngfactory files during Angular 2 AOT compilation?

I've noticed an interesting behavior when compiling my Angular 2 application with `ngc`. During the first run, it generates the `.ngfactory.ts` files for each component but only compiles the TypeScript to JavaScript for other files. This results in no ...

The import map is not being recognized by Supabase Edge Functions when passed in the command `npx supabase functions serve`

My situation involves two edge functions, namely create-payment-link and retrieve-payment-link. However, they are currently utilizing the import map located at /home/deno/flag_import_map.json, rather than the import_map.json file within the functions folde ...

Leveraging the ReturnType from a method within a Child class that inherits from an abstract class

I'm encountering an issue where TypeScript is throwing a lot of errors when trying to utilize the ReturnType of a method from an abstract class in a child class. Here's a simple example that illustrates the problem: Thank you abstract class Par ...

What is the process in TypeScript for defining a custom variation of a generic function?

Suppose we have a generic function: const f1 = <T>(x: T) => console.log(x) We can then create a specialized version for f1, like this: const f2 = (x: number) => f1(x) If we try to call f2 with an argument of type string, TypeScript will thr ...

Conceal the initial value in a dropdown menu in a React component

I've set up a codesandbox to demonstrate the issue (https://codesandbox.io/s/practical-flower-k6cyl?file=/src/App.tsx) Is there a way to prevent the "AGE" text (first option) in the select box from being selected again? It should only be visible when ...

Incorporate Material Design Icons into your NPM Electron React application for sleek visuals

I am currently exploring how to incorporate Material Design Icons into an NPM Electron project with Webpack 4. The Google Github page suggests that the icons can be easily installed using npm install material-design-icons. However, based on this discussion ...

Sorting through an array of objects using a filter method

While following a tutorial, I decided to make some changes to the TypeScript for learning purposes. However, I encountered a problem when trying to create a filter function from a React context script. I have successfully implemented a function called get ...

Jest encountered a syntax error due to an unexpected token <

When attempting to run a test using jest with a typescript preprocessor, I encountered the following error: var component = react_test_renderer_1["default"].create(<jumbotron_1["default"] />); ...

Error Alert: Missing Provider for FormGroup!

I have been working on an Angular application and recently created a Dialog component to serve as a model pop-up for user registration. Below is the code for the component: import { Component, OnInit, Inject } from '@angular/core'; import {MatDi ...