问题
I want to generate a HTML FORM from below JSON.
{
"templateName":"C-Learn Survey",
"surveyQuestions":[
{
"questionTitle":"Enter your name",
"questionType":"Text",
"questionGroup":{
}
},
{
"questionTitle":"Enter your empid:",
"questionType":"Text",
"questionGroup":{
}
},
{
"questionTitle":"Select your technologies",
"questionType":"Multi choice",
"questionGroup":{
"options":[
{
"optionText":"Java"
},
{
"optionText":"Mule"
},
{
"optionText":".net"
}
],
"showRemarksBox":false
}
},
{
"questionTitle":"Gender",
"questionType":"Single choice",
"questionGroup":{
"options":[
{
"optionText":"Male"
},
{
"optionText":"Female"
}
],
"showRemarksBox":false
}
}
]
}
for example
{
"questionTitle":"Enter your name",
"questionType":"Text",
"questionGroup":{
}
for the above json there should be a html form element like this
<label>Enter your name</label>
<input type="text" placeholder="Enter your name">
I am new to Angular and seen some post and code on internet saying that It is possible through jquery Please suggest me how to achieve that. I am using Angular 7.
回答1:
Try this Angular6-json-schema-form
Stackblitz example
In your typescript file
import { jsonSchema } from './jsonSchema';
jsonFormOptions = {
loadExternalAssets: false,
};
schema = {
"type": "object",
"properties": {
"first_name": { "type": "string" },
"last_name": { "type": "string" },
"address": {
"type": "object",
"properties": {
"street_1": { "type": "string" },
"street_2": { "type": "string" },
"city": { "type": "string" },
"state": {
"type": "string",
"enum": [ "AL", "AK", "AS", "AZ", "AR", "CA", "CO", "CT", "DE",
"DC", "FM", "FL", "GA", "GU", "HI", "ID", "IL", "IN", "IA",
"KS", "KY", "LA", "ME", "MH", "MD", "MA", "MI", "MN", "MS",
"MO", "MT", "NE", "NV", "NH", "NJ", "NM", "NY", "NC", "ND",
"MP", "OH", "OK", "OR", "PW", "PA", "PR", "RI", "SC", "SD",
"TN", "TX", "UT", "VT", "VI", "VA", "WA", "WV", "WI", "WY" ]
},
"zip_code": { "type": "string" }
}
},
"birthday": { "type": "string" },
"notes": { "type": "string" },
"phone_numbers": {
"type": "array",
"items": {
"type": "object",
"properties": {
"type": { "type": "string", "enum": [ "cell", "home", "work" ] },
"number": { "type": "string" }
},
"required": [ "type", "number" ]
}
}
},
"required": [ "last_name" ]
};
In your html file
<json-schema-form
[schema]="schema"
[layout]="layout"
[options]='jsonFormOptions'
[framework]="'bootstrap-4'"
(onSubmit)="onSubmit($event)"
(formSchema)="showFormSchemaFn($event)"
(formLayout)="showFormLayoutFn($event)">
</json-schema-form>
来源:https://stackoverflow.com/questions/58760464/how-to-generate-a-html-form-from-json-in-angular-7