Arrays 将表单中的数据添加到角度为2的数组中+
这是我的表格 在输入问题时,我可以根据您的意愿添加任意多的备选方案。 在操作中将是编辑备选方案的按钮 我希望我的数组具有以下格式:Arrays 将表单中的数据添加到角度为2的数组中+,arrays,angular,typescript,angular-reactive-forms,Arrays,Angular,Typescript,Angular Reactive Forms,这是我的表格 在输入问题时,我可以根据您的意愿添加任意多的备选方案。 在操作中将是编辑备选方案的按钮 我希望我的数组具有以下格式: { "Question": "Question test", "cod" : "pw3" "Value" : "10" "Alternatives": [ { "test": "test", "test2": "test", "test3": "test" }, ] } 当您单击“添加”按钮时,您可以添加
{
"Question": "Question test",
"cod" : "pw3"
"Value" : "10"
"Alternatives": [
{
"test": "test",
"test2": "test",
"test3": "test"
},
]
}
当您单击“添加”按钮时,您可以添加多个备选方案,但无限制数量
此代码使备选方案出现:
<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>
单击“保存”完成问题时,如何以这种方式填充数组?我认为您的字段选项有点错误,我认为应该是这样的:
"Alternatives: [{'test':'testAnswer'},{'test2':'test2Answer'}... ]
let form = {
"Question": "Question test",
"cod" : "pw3"
"Value" : "10"
"Alternatives": [
{
"test": "test",
"test2": "test",
"test3": "test"
},
]
};
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
}
然后,您还可以使用*ngFor对备选方案进行迭代
我会这样做:
"Alternatives: [{'test':'testAnswer'},{'test2':'test2Answer'}... ]
let form = {
"Question": "Question test",
"cod" : "pw3"
"Value" : "10"
"Alternatives": [
{
"test": "test",
"test2": "test",
"test3": "test"
},
]
};
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
}
然后,我将构造一个函数来添加/删除内部数组中的项,可能类似于:
"Alternatives: [{'test':'testAnswer'},{'test2':'test2Answer'}... ]
let form = {
"Question": "Question test",
"cod" : "pw3"
"Value" : "10"
"Alternatives": [
{
"test": "test",
"test2": "test",
"test3": "test"
},
]
};
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
}
当然,您应该更新html以迭代“form”新变量