我正在创建一个具有动态输入元素的应用程序。动态意味着那些输入将来自服务器端。这是psedo示例html:
<form>
<section1>
<static-field-1></static-field-1>
<static-field-2></static-field-2>
<dynamic-field-1></dynamic-field-1>
<dynamic-field-2></dynamic-field-2>
</section1>
<section2>//'a' postfix is just for differenting
<dynamic-field-1a></dynamic-field-1a>
<static-field-1a></static-field-1a>
<static-field-2a></static-field-2a>
<dynamic-field-2a></dynamic-field-2a>
</section2>
</form>
简而言之,包括其位置在内的所有表单呈现都将由服务器的api响应决定。
api响应将是这样的:
[
{
"section_pos":1,
"name":"section1",
"fields":[
{
"type":"static",
"name":"static-field-1"
},
{
"type":"static",
"name":"static-field-2"
},
{
"type":"dynamic",
"name":"dynamic-field-1",
"input":"text",
"validation":"required"
},
{
"type":"dynamic",
"name":"dynamic-field-2",
"input":"number",
"validation":"required"
}
]
},
{
"section_pos":2,
"name":"section2",
"fields":[
{
"type":"dynamic",
"name":"dynamic-field-1a",
"input":"text",
"validation":"required"
},
{
"type":"static",
"name":"static-field-1a"
},
{
"type":"static",
"name":"static-field-2a"
},
{
"type":"dynamic",
"name":"dynamic-field-2a",
"input":"number",
"validation":"required"
}
]
}
]
我将如何创建动态输入表单元素,并根据服务器发送的数据在各自的部分中将它们随机播放。
对于静态我的意思是,这些已经存在/我们已知。动态字段是服务器发送的一次。服务器还将发送每个字段(静态/动态)应该对齐的顺序。 需要帮助完成此任务
答案 0 :(得分:0)
希望我理解你的问题 如果要在服务器的响应顺序中将所有字段列为INPUT标记:
<div *ngFor="let section of mySuperProvider.getDataFromServer()">
<h2>{{section.name}}</h2>
<p *ngFor="let field of section.fields">
<b>{{field.name}}</b>
<input type="text" ... >
</p>
</div>
如果要重新填充字段,可以在提供程序中执行,或者:
<p *ngFor="let field of shuffle(section.fields)">
其中shuffle()是一个函数:
shuffle(array) {
return array.sort(function() { return 0.5 - Math.random() });
}
如果您只想显示特定类型并排除其他类型,则可以使用* ngIf。
如果你需要使用Configurable Reactive Forms而不是INPUT标签,那么请参阅本link中的好文章,主要思想是创建动态组件并将配置传递给它:
<form
class="dynamic-form"
[formGroup]="form"
(ngSubmit)="submitted.emit(form.value)">
<ng-container
*ngFor="let field of config;"
dynamicField
[config]="field"
[group]="form">
</ng-container>
</form>