Reputation: 517
This is my form
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?
Upvotes: 0
Views: 57
Reputation: 150
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
Upvotes: 1