angular - Angular,按钮需要单击 2 次才能更改文本
问题描述
我是 Angular 的初学者,这是一个测验应用程序,我遇到了一个问题,即单击按钮需要单击 2 次。第一次单击时,它工作正常,但是当我单击任何按钮时,下一步和返回按钮需要双击才能返回或下一个问题旁边。
html:
<div class="qblock" *ngIf="search">
<div class="qheader">
<h2>{{ search.questionNumber }}</h2>
</div>
<div class="qdescription">
<p>
{{ search.questionText }}
</p>
</div>
</div>
<div class="qactions text-right">
<button class="btn btn-secondary" (click)="previous(search.index)">
Back
</button>
<button class="btn btn-primary" (click)="next(search.index)">
Next
</button>
</div>
组件.ts
public QuizData: any = {};
public number = 0;
public search: any;
constructor(private cd: ChangeDetectorRef) {
this.QuizData = [
{
index: 0,
questionNumber: 'Question 1',
questionText:
'Test question 1',
options: [
{
optionLabel: 'A',
optionText: 'Option A',
optionActive: false,
},
{
optionLabel: 'B',
optionText: 'Option B',
optionActive: false,
},
{
optionLabel: 'C',
optionText: 'Option C',
optionActive: false,
},
{
optionLabel: 'D',
optionText: 'Option D',
optionActive: false,
},
],
},
{
index: 2,
questionNumber: 'Question 2',
questionText:
'Test question 2',
options: [
{
optionLabel: 'A',
optionText: 'Option A',
optionActive: false,
},
{
optionLabel: 'B',
optionText: 'Option B',
optionActive: false,
},
{
optionLabel: 'C',
optionText: 'Option C',
optionActive: false,
},
{
optionLabel: 'D',
optionText: 'Option D',
optionActive: false,
},
],
},
];
this.number = 0;
let currentQuestion = this.QuizData[this.number];
this.number = this.number + 1;
this.search = currentQuestion;
}
next(index) {
let count = Object.keys(this.QuizData).length;
index = index + 1;
if (this.number == count) {
alert('you reached last index');
this.number = this.number - 1;
return;
}
let nextQuestion = this.QuizData[this.number];
if (this.number < count) {
this.number = this.number + 1;
}
this.search = nextQuestion;
}
previous(index) {
index = index - 1;
this.number = this.number - 1;
if (this.number < 0) {
this.number = 0;
return;
}
let previousQuestion = this.QuizData[this.number];
this.search = previousQuestion;
}
解决方案
this.number = this.number + 1;
从构造函数中移除。你的第一个索引是 0;
然后更新您的活动,如下所示
next(index) {
let count = Object.keys(this.QuizData).length;
this.number++;
if (this.number == count) {
alert('you reached last index');
this.number --;
return;
}
let nextQuestion = this.QuizData[this.number];
this.search = nextQuestion;
}
previous(index) {
this.number --;
if (this.number < 0) {
this.number = 0;
return;
}
let previousQuestion = this.QuizData[this.number];
this.search = previousQuestion;
}
推荐阅读
- vba - 我需要帮助循环使用 Excel VBA 的 if 语句中的索引/匹配
- swift - 如何在swift中集成TPKeyboardavoiding?
- visual-studio-2017 - 如何配置 Visual Studio 2017 在发布时不生成 nuget 包作为输出
- ios - 在项目结构中找不到来自故事板的自定义视图控制器
- javascript - 如何使用 Google Calendar API v3 (JavaScript) 移除事件通知
- python - 为 2D numpy 数组形成协方差矩阵
- android - Kivy App 立即在 android 上崩溃,陷入循环
- php - 如何在php中获取空索引foreach循环
- google-sheets - 使用 apikey 从 Google Sheets API 获取 403
- javascript - ES6 等价于 lodash _.mapValues