我正在使用 ng-formly npm 工具创建动态表单。我希望此表单分为部分和选项卡,但仍然有一个提交按钮。即单个标签。现在我根据该库的文档。我创建了这个名为 TabType 的接口,它包含特定选项卡的差异字段。
export interface TabType {
label: string;
fields: FormlyFieldConfig[]
}
现在使用下面的变量和模式,我可以使用上面的 TabType 接口生成分为不同部分的表单。
form = new FormGroup({});
model = {};
options: FormlyFormOptions = {};
tabs: TabType[] = [
{
label: 'Personal data',
fields: [
{
className: '',
template: '<strong>Basic Information:</strong>',
},
{
fieldGroupClassName: '',
fieldGroup: [
{
className: 'mdc-text-field__input',
type: 'input',
key: 'firstName',
templateOptions: {
label: 'First Name',
},
},
{
className: 'mdc-text-field__input',
type: 'input',
key: 'lastName',
templateOptions: {
label: 'Last Name',
},
expressionProperties: {
'templateOptions.disabled': '!model.firstName',
},
},
],
},
{
className: '',
template: '<strong>Address:</strong>',
},
{
fieldGroupClassName: '',
fieldGroup: [
{
className: 'row',
type: 'input',
key: 'street',
templateOptions: {
label: 'Street',
},
},
{
className: 'mdc-text-field__input',
type: 'input',
key: 'cityName',
templateOptions: {
label: 'City',
},
},
{
className: 'mdc-text-field__input',
type: 'input',
key: 'zip',
templateOptions: {
type: 'number',
label: 'Zip',
max: 99999,
min: 0,
pattern: '\\d{5}',
},
},
],
},
{
className: '',
template: '<strong>Other Inputs:</strong>',
},
{
type: 'textarea',
key: 'otherInput',
templateOptions: {
label: 'Other Input',
},
},
{
type: 'checkbox',
key: 'otherToo',
templateOptions: {
label: 'Other Checkbox',
},
},
],
},
{
label: 'Destination',
fields: [
{
key: 'country',
type: 'input',
templateOptions: {
label: 'Country',
required: true,
},
},
],
},
{
label: 'Day of the trip',
fields: [
{
key: 'day',
type: 'input',
templateOptions: {
type: 'date',
label: 'Day of the trip',
required: true,
},
},
],
},
];
现在,在创建这个变量之后,我正在创建一个名为“form”的 FormArray,如下所示,
form = new FormArray(this.tabs.map(() => new FormGroup({})));
最后在 HTML 文件中,我有下面的代码,它通过选项卡解析以及称为“选项卡”数组的 TabType 并访问所需的表单字段以呈现它。
<div class="mdc-card">
<section class="mdc-card__primary view-section">
<h3>{{tab.label}}</h3>
</section>
<section class="mdc-card__supporting-text view-section-body">
<formly-form
[form]="form.at(index)"
[model]="model"
[fields]="tab.fields"
[options]="options">
</formly-form>
</section>
</div>
</div>
现在我想对表单元素再做一次迭代,并希望在选项卡中划分字段。在上面你可以看到它正在创建部分。
所以我看到的问题是,如果我们可以创建多维 FormArray,那么我们可以使用选项卡列表对其进行迭代,我们使用上面的部分列表完成。
有人可以建议我这样做的方法吗?
更新 :
form = new FormArray(this.tabs.map(() => new FormGroup({})));
const baseForm: FormGroup = this.fb.group({
tabs: this.fb.array([this.form,this.form,this.form])
})
现在上面的 baseForm 有所有三个选项卡数据(虽然相同),你能帮忙把它作为数组传递,以便我可以迭代它,因为我认为我不能在 html 中迭代 formgroup 对象。