绑定(bind)到 Angular 中按钮的索引增量函数不会增加索引,并且不会在单击按钮时迭代数组。无论我连续点击该按钮多少次,我首先看到的都是相同的 [0]
来自数组的问题。为什么会这样?
component.html
<div class="card-body">
<h5 class="card-title">{{questions}}</h5>
<input *ngFor="let answer of answers"
type="radio" name="ans" [value]="answer"> {{answer}}<br>
<button class="btn btn-primary" (click)="nextQuestion()">Go somewhere</button>
</div>
component.ts
export class QuostionnaireComponent implements OnInit {
questions:any;
answers:any;
correstAnswers:any;
incremental:Observable = 0;
constructor(private questionnaire: QuestionnaireService) {
this.questions = this.questionnaire.theQuestion[this.incremental];
this.answers = this.questionnaire.theChoices[this.incremental];
}
nextQuestion():void {
this.incremental++;
}
ngOnInit() {
}
}
如何在按钮单击时正确迭代一系列问题和答案?
此外,在我的单选按钮中,值工作正常,我将所有三个答案选项绑定(bind)到 [value]
但单选按钮旁边没有文字,就像我的> {{answer}}<br>
被忽略。不过没有错误。感谢您的帮助。
最佳答案
尝试 setter/getter 。每次 Angular 的更改检测启动并重新获取页面数据时,getter 都会执行。
export class QuostionnaireComponent implements OnInit {
get questions(): any{
return this.questionnaire.theQuestion[this.incremental];
}
get answers(): any{
return this.questionnaire.theChoices[this.incremental];
}
correstAnswers:any;
incremental: number = 0;
constructor(private questionnaire: QuestionnaireService) { }
nextQuestion():void {
this.incremental++;
}
ngOnInit() {
}
}
关于javascript - 绑定(bind)到 Angular 中按钮的索引增量函数不会增加索引,也不会迭代数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53751163/