【发布时间】:2022-09-24 04:25:12
【问题描述】:
我正在尝试构建一个完整的动态网页。
到目前为止,这是我的代码:
我的 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} 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;
answer!: FormGroup;
result1?: String;
result2?: String;
constructor(private quiz1Service: Quiz1Service) { }
ngOnInit(): void {
this.retrieveQuestions();
this.answer = new FormGroup({
Ans1: new FormControl(\'\'),
Ans2: new FormControl(\'\')
});
}
retrieveQuestions(): void {
this.quiz1Service.getAll()
.subscribe({
next: (data: any) => {
this.questions = data;
console.log(data);
},
error: (e: any) => console.error(e)
});
}
onSubmit(){
this.result1 = this.answer.value.Ans1;
this.result2 = this.answer.value.Ans2;
}
}
这是我的component.html
<div class=\"container\">
<Form >
<div [formGroup]=\"answer\">
<div *ngFor=\"let question of questions\">
<a>{{question.questionId}}. {{question.question}}</a><br>
<input type=\"radio\" formControlName=\"Ans{{question.questionId}}\" value=\"A\" >
<label for=\"html\">A. {{question.optionsA}}</label><br>
<input type=\"radio\" formControlName=\"Ans{{question.questionId}}\" value=\"B\" >
<label for=\"html\">B. {{question.optionsB}}</label><br>
<input type=\"radio\" formControlName=\"Ans{{question.questionId}}\" value=\"C\" >
<label for=\"html\">C. {{question.optionsC}}</label><br>
<input type=\"radio\" formControlName=\"Ans{{question.questionId}}\" value=\"D\" >
<label for=\"html\">D. {{question.optionsD}}</label><br>
</div>
</div>
<button class=\"btn btn-primary \" (click)=\"onSubmit()\" type=\"button\" >Submit</button>
</Form>
<div ng-if=\"result1 != null\">
<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>
<td>{{result1}}</td>
</tbody>
</table>
</div>
</div>
我想做的是:
首先,我想根据问题中的记录数在表单组内动态创建新的表单控件。
然后,我想将 ans1、ans2、... 的值存储在数组中,而不是 result1 和 result2。
最后。我想在 html 中的表格内显示该数组,而不是结果 1。
我尝试了各种方法,但一直出错,请问有人可以帮助我吗?
-
您能否创建一个 StackBlitz 示例,其中还包含您的 Quiz1 模型 +
this.quiz1Service.getAll()的一些模拟数据?
标签: html angular typescript dynamic