【发布时间】:2019-11-12 12:27:10
【问题描述】:
我正在从 API 获取表单组件。我的代码能够从 JSON 生成 HTML FORM。生成表单并在单击提交时填写数据后,我低于 JSON
{
"Enter Your Name": "Abhishek",
"Enter Your Empid": 55555,
"Gender": "Male",
"Skills": true
}
我从用户那里获取数据的 HTML FORM:
<mat-card>
<h1 >{{templateName}}</h1>
<br>
<form [formGroup]="myFormGroup" (ngSubmit)="onSubmit()">
<div *ngFor="let form_elem of formTemplate">
<div [ngSwitch]="form_elem.questionType">
<div *ngSwitchCase="'Text'">
<label>{{form_elem.questionTitle}}: </label>
<mat-form-field class="full-width">
<input matInput type="text" placeholder="{{form_elem.questionTitle}}" formControlName="{{form_elem.questionTitle}}"/>
</mat-form-field>
</div>
<div *ngSwitchCase="'Number'">
<label>{{form_elem.questionTitle}}: </label>
<mat-form-field class="full-width">
<input matInput type="Number" placeholder="{{form_elem.questionTitle}}" formControlName="{{form_elem.questionTitle}}"/>
</mat-form-field>
</div>
<div *ngSwitchCase="'Single choice'">
<label>{{form_elem.questionTitle}}: </label><br><br>
<mat-radio-group class = "tp-radio-group" formControlName="{{form_elem.questionTitle}}">
<mat-radio-button class = "tp-radio-button"
*ngFor = "let options of form_elem.questionGroup.options" [value] = "options.optionText">
{{options.optionText}}
</mat-radio-button>
</mat-radio-group>
</div>
<div *ngSwitchCase="'Multi choice'">
<label>{{form_elem.questionTitle}}: </label><br><br>
<mat-checkbox class = "tp-margin" *ngFor = "let options of form_elem.questionGroup.options" formControlName = "{{form_elem.questionTitle}}">
{{options.optionText}} </mat-checkbox>
</div>
<br>
</div>
</div>
<button mat-fab value="Submit">Submit</button>
</form>
</mat-card>
从文本、数字和无线电可以看出,它给出了值,但对于“技能”的复选框组件,它显示为真。我想要选中的复选框值而不是“true”。
HTML FORM 是动态的,从下面的 JSON 生成
"surveyQuestions": [
{
"questionTitle": "Enter Your Name",
"questionType": "Text",
"questionGroup": {}
},
{
"questionTitle": "Enter Your Empid",
"questionType": "Number",
"questionGroup": {}
},
{
"questionTitle": "Gender",
"questionType": "Single choice",
"questionGroup": {
"options": [
{
"optionText": "Male"
},
{
"optionText": "Female"
}
],
"showRemarksBox": false
}
},
{
"questionTitle": "Skills",
"questionType": "Multi choice",
"questionGroup": {
"options": [
{
"optionText": "C"
},
{
"optionText": "Java"
},
{
"optionText": "Mule"
}
],
"showRemarksBox": false
}
}
]
在我的 Component.ts 中
ngOnInit() {
let group={}
this.form_template.forEach(input_template=>{
group[input_template.questionTitle]=new FormControl('');
})
this.myFormGroup = new FormGroup(group);
}
onSubmit() {
console.log(JSON.stringify(this.myFormGroup.value));
}
请建议我如何在 json 中获取该复选框的值。
【问题讨论】:
标签: javascript json angular angular7 dynamicform