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:
-> Here, I used[(ngModel)]="question.answers[index]"
let index=index;
withinngFor
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.