1
我有一個表單來創建一個「問題」,它是一個包含答案字符串數組的對象。我的問題是,我無法找到綁定這些問題的答案模型從json對象綁定數組到Angular2中使用ngModel的表單
辦法一個天真的實行將是:
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(){};
}
問題是在第二ngModel
。 有了這個解決方案,我得到的錯誤:
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!
我想我們不能生成值從ngFor結合的典範。
我也嘗試這些選項:
[(ngModel)]="question.answers[index]"
- >有了這個,我就ngFor
添加let index=index;
和相應名稱的輸入。在這裏,我有我在下一段描述的錯誤[(ngModel)]="question.answers[]
- >嘗試做同樣的事情,你使用純HTML。這根本不起作用
沒有一個像我期望的那樣工作:當你改變輸入值時,它似乎重新加載了ngFor循環。當我擴展我的解決方案以允許用戶追加或刪除答案時,添加答案會刪除第一個答案的內容。
得到它......這傢伙有第二陣列做了,但我覺得有點不可思議...... http://plnkr.co/edit/PO9ujHLWfzvYD67nDCwT?p=preview 你真的需要一個數組還是你也可以遍歷一個對象?你可以寫一個管道來做到這一點:http://stackoverflow.com/questions/35534959/access-key-and-value-of-object-using-ngfor – Riscie
這兩個解決方案都非常好的調整,可以解決我的問題(不很好雖然)。請相應地編輯您的答案,以便我可以驗證它。 我真的需要一個數組,因爲我添加,刪除元素,我需要一個從0到長度的索引 - 1.我可以用一個對象來做,但它似乎矯枉過正 –