javascript - 绑定(bind)到 Angular 中按钮的索引增量函数不会增加索引,也不会迭代数组

标签 javascript arrays angular loops ngfor

绑定(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/

相关文章:

arrays - 将嵌入空格的文件名读取到 shell 脚本中的数组中

java - 如何将数组长度划分为长度为 3 倍数的数组

PHP,使用所有其他数组值

javascript - 垂直滚动时不允许水平滚动(反之亦然)

javascript - 单击时捕获链接 (<a>) 元素中的文本

javascript - 我们可以在 Javascript 中将 Unicode 转换为 ASCII 吗? charCodeAt() 仅适用于 Unicode?

javascript - 如何在 Chrome 和 Firefox 中将此字符串转换为 Javascript 日期?

JavaScript;如何在三位数字后设置点?

angular - WebStorm 是如何识别 Angular 语言服务的?

javascript - Angular 2 选择选项(下拉)-如何获取更改值以便在函数中使用它?