Ulysse BN Ulysse BN - 1 month ago 41
TypeScript Question

Bind array from a json object to a form using ngModel in Angular2

I have a form to create a "question", which is an object containing an array of strings for answers. My issue is that I can’t find a way to bind those answers to the question model

A naive implemenation would be:

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

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);

Issue is on the second
With this solution I get 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!

I guess we can’t bind a generated value from an ngFor to a model.

I also tried these options:

  • [(ngModel)]="question.answers[index]"
    -> With this I added
    let index=index;
    and a corresponding name to the input. Here I have the error I’m describing on the next paragraph

  • [(ngModel)]="question.answers[]
    -> Trying to do the same you do using pure HTML. This doesn’t work at all

None of these worked as I expected: when you change value on an input it seems to reload the ngFor loop. And when I extended my solution to allow user to append or delete an answer, adding an answer would delete content of the first one.


As far as I can see you have two options:

1 Use an Object instead of an array

You can iterate over the object using ngFor and a pipe like described here: Iterate 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 Use a second array for the ngFor loop like here http://plnkr.co/edit/PO9ujHLWfzvYD67nDCwT?p=preview

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

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

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