[英]How to properly store and use data from ng Form
到目前為止,這是我的代碼:
我的組件.html:
<div class="container">
<Form #a ="ngForm" ngForm (ngSubmit)="onSubmit(a)">
<div *ngFor="let question of questions">
<div class = "form-group">
<a>{{question.questionId}}. {{question.question}}</a><br>
<input type="radio" ngModel name="Ans{{question.questionId}}" value="A" >
<label for="html">A. {{question.optionsA}}</label><br>
<input type="radio" ngModel name="Ans{{question.questionId}}" value="B" >
<label for="html">B. {{question.optionsB}}</label><br>
<input type="radio" ngModel name="Ans{{question.questionId}}" value="C" >
<label for="html">C. {{question.optionsC}}</label><br>
<input type="radio" ngModel name="Ans{{question.questionId}}" value="D" >
<label for="html">D. {{question.optionsD}}</label><br>
</div>
</div>
<button class="btn btn-primary " type="submit" >Submit</button>
</Form>
<div *ngIf="results.length >0">
<table>
<thead>
<th>Question No.</th>
<th>Correct Answer</th>
<th>Your Answer</th>
</thead>
<tbody *ngFor="let question of questions">
<td>{{question.questionId}}</td>
<td>{{question.answer}}</td>
</tbody>
</table>
{{score}}
{{results.length}}
</div>
</div>
和我的component.ts:
import { Component, OnInit } from '@angular/core';
import { Quiz1 } from 'src/app/models/quiz1.model';
import { Quiz1Service } from 'src/app/services/quiz1.service';
import {FormControl, FormGroup, NgForm} from '@angular/forms';
@Component({
selector: 'app-quiz1',
templateUrl: './quiz1.component.html',
styleUrls: ['./quiz1.component.css']
})
export class Quiz1Component implements OnInit {
questions?: Quiz1[];
currentQuestion: Quiz1 = {};
currentIndex = -1;
score = 0;
results:String[] = [];
//index?: String[] = ['Ans1','Ans2'];
constructor(private quiz1Service: Quiz1Service) { }
ngOnInit(): void {
this.retrieveQuestions();
}
retrieveQuestions(): void {
this.quiz1Service.getAll()
.subscribe({
next: (data: any) => {
this.questions = data;
console.log(data);
},
error: (e: any) => console.error(e)
});
}
onSubmit(a:NgForm){
this.results?.push(a.value);
console.log(this.results);
console.log(this.results.length)
this.questions?.forEach((questions) => {
console.log(questions.questionId);
if(questions.answer==this.results[questions.questionId-1]){
this.score++
console.log(this.score)
}
});
}
}
當我在控制台中打印結果數組時,這就是我得到的:
Array(1)
0: {Ans1: 'A', Ans2: 'C'}
length: 1
[[Prototype]]: Array(0)
如您所見,它將所有數據存儲在一個索引中,並且字段名稱根本不起作用。
我想要的只是存儲在數組中不同索引中的字段數據,所以我可以使用它。
那可能嗎?
我不認為你可以使用模板驅動的 forms 來實現你想要的。
您將不得不使用反應式 forms 和FormArray
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.