0

This is my form

enter image description here

When entering a question, I can add as many alternatives as you wish. In action would be the button to edit alternative.

I would like my array to have this format:

{
"Question": "Question test",
"cod" : "pw3"
"Value" : "10"
  "Alternatives": [
    {
      "test": "test",
      "test2": "test",
      "test3": "test"
    },
  ]
}

When you click the add button you can add several alternatives, do not have a limit number

This code is what makes the alternatives appear:

<table>
    <thead><tr><th>Name</th><th>Action</th></tr>
    </thead>
    <tbody>
      <tr *ngFor="let quiz of quizes">
        <td>
          <input name="alternativa" type="text" [(ngModel)]="quiz.pergunta" [disabled]="!quiz.isEditable"/>
        </td>
        <td>
          <button (click)="quiz.isEditable=!quiz.isEditable" *ngIf="!quiz.isEditable">Edit</button>
          <button *ngIf="quiz.isEditable" (click)="quiz.isEditable=!quiz.isEditable">Save</button>
        </td>
      </tr>
    </tbody>
  </table>

  <div class="ui-g-2 ui-md-2 ui-lg-2 ui-fluid espacamento-baixo">
    <p-button label="Salvar"></p-button>
  </div> 

How can I populate the array this way when I click Save to complete the question?

1
  • Form arrays is what you're looking for Commented May 24, 2019 at 12:50

1 Answer 1

1

I think your field "Alternatives" is a bit wrong, I think it should be like this:

"Alternatives: [{'test':'testAnswer'},{'test2':'test2Answer'}... ]

Then, you can iterate over alternatives with *ngFor as well

I would do something like this:

let form = {
"Question": "Question test",
"cod" : "pw3"
"Value" : "10"
"Alternatives": [
  {
  "test": "test",
  "test2": "test",
  "test3": "test"
  },
 ]
};

then, I would structure a function to add/remove the items in the inside array, maybe something like this:

public addOrRemoveItemInArray(a:boolean) {
// if a=true, add if false = remove
if (a === true) { 
let newAnswer = {"test": ""};
this.form.Alternatives.push(newAnswer);

  }
if (a=== false) { this.form.Alternatives.pop() //remove the las item
  }
else {}//just to avoid problems
}

of Course, you should update the html to iterate over 'form' new variable

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.