ngModel with ngForおよびtrackBy:trackByIndexが期待通りに動作しません。 これは私のHTMLテンプレートです:カスタムモデルでngForおよびngModelを使用する際の問題
<form (ngSubmit)="createTest()" #testForm="ngForm">
<div class="card" *ngFor="let question of questionsArr; let i=index;">
<div class="card-header">
<input type="text" placeholder="Question {{i+1}}" name="question{{i}}" class="form-control" [(ngModel)]="questionsArr[i].text">
</div>
<div class="card-block" *ngFor="let option of fillArray(oC); let u=index">
<input type="text" class="form-control" placeholder="Option {{u+1}}" name="option" id="option">
</div>
</div>
</form>
The below works well. But in the above, [(ngModel)]="questionsArr[i].text" seems to bind to the same thing regardless.
<label *ngFor="let item of items; let i=index; trackBy:trackByIndex">
{{items[i]}}
<input type="number" [(ngModel)]="items[i]">
</label>.
私はいくつかのテストを行なったし、オブジェクトの以下の配列を使用してオブジェクトの配列を使用し、そのになって、それが動作します:
testarr = [
{
a: "a",
b: "b"
},
{
a: "aa",
b:"bb"
}
];
いくつかのテストを行うには、出来た。 ngModel
をちょうどquestionsArr[i]
に変更すると、繰り返しごとに別々のオブジェクトが生成されました。問題は、[(ngModel)]="questionsArr[i].text"
がそのように動作していないようです。これは、関連する私のコンポーネントの一部である「new QuestionModel("Question Text", this.s.name, "",null);
」
:
questionsArrはこれを単なる配列である私がtrackBy
を使用するよ集まってきたものから、
optionsArr: OptionModel[];
questionsArr: QuestionModel[];
blankQM: QuestionModel;
blankOM: OptionModel;
formTest: TestModel;
items: number[] = [1,2,3,4,5];
constructor(
private api: ApiService
) { }
ngOnInit() {
this.blankQM = new QuestionModel("Question Text", this.s.name, "",null);
this.blankOM = new OptionModel("Option Text");
this.formTest = new TestModel("", null);
this._getQuestionArrays();
this._getOptionArrays();
}
_getQuestionArrays(){
// this.fillArray(this.qC);
this.questionsArr = Array(this.qC).fill(this.blankQM);
}
_getOptionArrays(){
// this.fillArray(this.oC);
this.optionsArr = Array(this.oC * this.qC).fill(this.blankOM);
}
fillArray(qty){
return Array(qty).fill(0).map((e,i)=> i+ 1);
}
goBack(){
this.back.emit();
}
createTest(){
console.log(this.questionsArr);
// console.log(this.optionsArr);
console.log(this.testarr);
}
trackByIndex(index: number, value: QuestionModel){
return index;
}
testarr = [
{
a: "a",
b: "b"
},
{
a: "aa",
b:"bb"
}
];
}
、それそれは何を想定している、私はなぜ私は傾けるngModel
それは正しいにバインドするquestionsArr[i].text
questionsArr
の正しいインデックスのテキストプロパティにアクセスする質問をアクセスするにはenter code here
十分に動作します。
[(ngModel)]にバインドしようとするとどうなりますか? – BogdanC
私はエラーを起こさない。ちょうど、ngModelをquestionsArr [I] .textにバインドすると、配列内の最後の項目にのみバインドされる。それは期待どおりにそれを追跡しません。同じ項目をすべての入力にバインドします。 –