【问题标题】:Shuffle objects in a FormArray在 FormArray 中随机播放对象
【发布时间】:2020-04-27 06:56:21
【问题描述】:

我正在开发一个考试模拟器。我创建了一个多项选择题考试,我想每次都随机播放可能的答案,但我找不到答案..

我目前的代码:

TS

loadForm(data) {
  this.maxindex = data.length;
  this.status = 1
  for (let ques = 0; ques < data.length; ques++) {
    const questionsFormArray = this.examForm.get("questions") as FormArray;
    questionsFormArray.push(this.question);
    for (let opt = 0; opt < data[ques].options.length; opt++) {
      const optionsFormsArray = questionsFormArray.at(ques).get("options") as FormArray;
      optionsFormsArray.push(this.option);
    }
  }
  this.examForm.controls.questions.patchValue(data);
}

HTML

<div formArrayName="questions">
 <div *ngFor="let question of examForm.get('questions').controls;let questionIndex=index"
   [formGroupName]="questionIndex">
   <div *ngIf="questionIndex==index">
    <label>{{questionIndex+1}}) {{examForm.value.questions[questionIndex].description}} </label>
     <br />
      <div formArrayName="options">
       <div *ngFor="let option of question.get('options').controls; let optionIndex=index"
         [formGroupName]="optionIndex">
         <input type="checkbox" formControlName="selected" value=""(change)="checkValue(questionIndex. 
            optionIndex)"/>
         {{examForm.value.questions[questionIndex].options[optionIndex].response}}
       </div>
     </div>
   </div>
  </div>
 </div>

这是我每次都想洗牌的optionsFormsArray,有人可以帮忙吗?

【问题讨论】:

    标签: html angular typescript formarray formgroups


    【解决方案1】:

    你可以像这样洗牌。

    optionsFormsArray.sort( () =&gt; Math.random() - 0.5) );

    【讨论】:

    • 在创建 formArray 之前对“数据”进行洗牌
    • 那么在第二个 for 循环将其分配为 FormArray 之后,在循环内只需在普通数组中推送/随机播放?
    猜你喜欢
    • 2017-11-11
    • 2018-10-28
    • 1970-01-01
    • 2023-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多