0

我已经尝试了几个小时,但不知道如何比较不同对象中的字符串。

基本上我以对象(exerciseForm)的形式获得输入,我想将它的值与exercise.question.answer 属性的值进行比较。之后,我需要使用布尔值根据答案的正确性显示一个 div。

我可以以硬编码的形式轻松完成所有这些工作,但是当它在 ngFor 中时,我正在苦苦挣扎。我尝试的一种方法是创建一组答案并将其与一组输入进行比较,但我的 javascript 技能水平阻止了我。

模板:

<section class="exercises">
  <form
    fxLayout="column"
    fxLayoutGap="2px"
    [formGroup]="exerciseForm"
    (ngSubmit)="onSubmit(exerciseForm.value)"
  >

    <ul *ngFor="let exercise of exercises">
      <li>{{ exercise.instruction }}</li>
      <ul *ngFor="let question of exercise.questions">
        <li>
         {{ question.prefix }}
          <mat-form-field>
            <input
              name="answer"
              type="text"
              id="answer"
              matInput
              [formControlName]="question.id">
          </mat-form-field>

          {{ question.sufix }} -
          {{ question.translation }}
        </li>
      </ul>
    </ul>
    <button type="submit" mat-raised-button color="primary">Submit</button>
  </form>
</section>

.ts

import { Component, OnInit, Input } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { Question } from "./question.model";
import { Exercise } from './exercise.model';
import { TestAnswer } from './testanswer.model';


@Component({
  selector: 'app-exercisetests',
  templateUrl: './exercisetests.component.html',
  styleUrls: [ './exercisetests.component.scss' ]
})
export class ExerciseTestsComponent implements OnInit {
  exerciseForm: FormGroup;

  exercises: Exercise[]=[
    new Exercise (
      'Answer this question',
      [new Question (1, 'Eu','maluco','I am crazy','sou'),
       new Question (2, 'Eu','doidinho','I am cuckoo','estou')],
    )]

  constructor(private fb: FormBuilder) { }



  ngOnInit(): void {
    this.createGroup()

  }

   getAnswersArray() {

  }

  createGroup() {
    this.exerciseForm = this.fb.group({})
    this.exercises[0].questions.forEach(control =>
    this.exerciseForm.addControl(control.id.toString(), this.fb.control('')))
  }

  onSubmit(answer: TestAnswer) { 
    console.log (this.exercises)
    let answers = []
    let answersInput=[]
    this.exercises[0].questions.forEach(pergunta=> {
      answers.push(pergunta.answer)
      console.log(answers)
      return answers
    })

console.log (this.exerciseForm.value)

堆栈闪电战: https ://stackblitz.com/edit/angular-dzzzql

4

1 回答 1

0

要比较两个对象的特定属性,您可以执行以下操作:

const firstObject = {
    property1: "answer1",
    property2: "answer2",
    property3: "answer3"
};

const correctAnswers = {
    property1: "answer1",
    property2: "answer2",
    property3: "answer3"
 };


 const everythingIsRight = Object.keys(firstObject)
     .every(key => firstObject[key] === correctAnswers[key]); //true
于 2020-03-12T19:24:44.783 回答