将表单中的数据添加到数组 angular 2+
Add data from a form to array an angular 2+
这是我的表格
输入问题时,我可以根据需要添加任意多个选项。
在行动中将是编辑备选方案的按钮。
我希望我的数组具有以下格式:
{
"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"有点不对,我觉得应该是这样的:
"Alternatives: [{'test':'testAnswer'},{'test2':'test2Answer'}... ]
然后,您也可以使用 *ngFor 迭代备选方案
我会这样做:
let form = {
"Question": "Question test",
"cod" : "pw3"
"Value" : "10"
"Alternatives": [
{
"test": "test",
"test2": "test",
"test3": "test"
},
]
};
然后,我会构造一个函数来 add/remove 内部数组中的项目,可能是这样的:
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' 新变量
这是我的表格
输入问题时,我可以根据需要添加任意多个选项。 在行动中将是编辑备选方案的按钮。
我希望我的数组具有以下格式:
{
"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"有点不对,我觉得应该是这样的:
"Alternatives: [{'test':'testAnswer'},{'test2':'test2Answer'}... ]
然后,您也可以使用 *ngFor 迭代备选方案
我会这样做:
let form = {
"Question": "Question test",
"cod" : "pw3"
"Value" : "10"
"Alternatives": [
{
"test": "test",
"test2": "test",
"test3": "test"
},
]
};
然后,我会构造一个函数来 add/remove 内部数组中的项目,可能是这样的:
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' 新变量