简体   繁体   English

使用Angular2中的ngModel将数组从json对象绑定到表单

[英]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>;
}

@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(){};
}

Issue is on the second ngModel . 问题在第二个ngModel 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. 我猜我们不能将ngFor的生成值绑定到模型。

I also tried these options: 我还尝试了以下选项:

  • [(ngModel)]="question.answers[index]" -> With this I added let index=index; [(ngModel)]="question.answers[index]" ->为此,我添加了let index=index; on ngFor and a corresponding name to the input. ngFor上输入相应的名称。 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 [(ngModel)]="question.answers[] ->尝试执行与使用纯HTML相同的操作。这根本不起作用

None of these worked as I expected: when you change value on an input it seems to reload the ngFor loop. 这些都不如我预期的那样工作:当您更改输入的值时,似乎会重新加载ngFor循环。 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 1使用对象而不是数组

You can iterate over the object using ngFor and a pipe like described here: Iterate over TypeScript Dictionary in Angular 2 您可以使用ngFor和类似此处所述的管道对对象进行迭代在Angular 2中对TypeScript字典进行迭代

@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 2将第二个数组用于ngFor循环,例如此处http://plnkr.co/edit/PO9ujHLWfzvYD67nDCwT?p=preview

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM