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
.
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 addedlet index=index;
onngFor
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.