Angular-是否可以从非预定义对象创建FormGroup



因此,通常在angular中构建FormGroups时,您通常知道如何标记或命名每个字段或FormControl,因为通常情况下,您知道表单必须事先控制和验证的属性。例如,对于以前已知的myHouse对象,我可以执行以下操作:

myHouse = new FormGroup({
door: [''],
size: [''],
windows: new FormGroup({
size: [''],
clarity: ['']
...
});
})

你明白了。但我目前正在创建一个组件,我想把它用作我的应用程序的侧过滤栏。关键是我希望这个组件是可重复使用的,并且由于这个流程的需要,它的工作方式如下:

  • 父组件构建一个我命名为filterPreferences的对象数组,并将其传递给我的Filter组件,后者将其作为@Input((接收。对象将如下所示:

    this.filterPreferences = [{
    filterName: 'status',
    filterKey: 'Estado',
    options: [
    {
    optionName: 'open',
    optionKey: 'Abierta'
    },
    {
    optionName: 'closed',
    optionKey: 'Cerrada'
    },
    {
    optionName: 'ended',
    optionKey: 'Finalizada'
    }
    ]
    

    以及之后的更多对象。}]

  • 在此对象数组中,filterName指参数的类型,而optionName指所述参数可以具有的不同选项(项的状态可以是打开关闭结束(。用于i18l翻译的filterKey和optionKey属性。

  • 子组件(Filter组件(将接收该对象数组,并在此基础上构建FormGroup或FormArray,这样,当用户完成一系列筛选器的选择时,子组件可以将该选择传递回其相应的父组件。

这里的关键是,我的组件无法从一开始就知道字段或参数,就像前面的houseFormGroup示例一样。不同的父组件可以向该组件传递不同的信息块。每个父组件都将使用相同的filterNames、filterKeys、optionNames等结构,但每个参数的条目数和名称会有所不同。

试图用一种伪代码来说明我(失败的(尝试,我觉得我应该做的是:

--在我的声明中,const formArray=this.formBuilder.array([](;

createForm() {
this.filterPreferences.forEach((item) => {
const optionNames = item.options.map(( opt ) => opt.optionName);
item.FilterName = new FormGroup({
optionNames = new FormControl('');
})
this.formArray.push(item.filterName);
)}
}

本质上是对我的filterPreferences对象或对象数组进行迭代,并为每个对象构建一个formGroup。此表单的html如下所示:

<div class="filters" [formGroup]="formGroup">
<ng-container *ngFor="let filter of filterPreferences">
<div class="filter-options">
<h4>{{filter.filterKey}}</h4>
<div *ngFor="let options of filter.options">
<app-checkbox-input
formControlName="{{options.optionName}}"
class="float-left mr-3 mb-3"
[label]=" options.optionKey ">
</app-checkbox-input>
</div>
</div>
</ng-container>
</div>

我该如何解决这个问题?

我解决了大部分问题。

我犯的一个主要错误是没有意识到,实际上,我的每个"选项"块都是在自己的formGroup中创建的。所以我缺少的一个关键元素是:

<div class="filters" [formGroup]="formGroup">
<ng-container *ngFor="let filter of filterPreferences">
<div class="filter-options">
---- a new div for the formGroups ------
<div formGroupName="{{filter.filterName}}">
<h4>{{filter.filterKey}}</h4>
<div *ngFor="let options of filter.options">
<app-checkbox-input
formControlName="{{options.optionName}}"
class="float-left mr-3 mb-3"
[label]=" options.optionKey ">
</app-checkbox-input>
</div>
</div>
----- end of the new div -----
</div>
</ng-container>
</div>

注意新分区中formGroupname的引用。

例如,在以下块中:

filterName: 'status',
filterKey: 'Estado',
options: [
{
optionName: 'open',
optionKey: 'Abierta'
},
{
optionName: 'closed',
optionKey: 'Cerrada'
},
{
optionName: 'ended',
optionKey: 'Finalizada'
}
]

My.ts创建此表单组:

status: this.formBuilder.group({
open: [''],
closed: [''],
ended: ['']
})

然后,我的html可以在它的"let options of filter.options"上迭代,因为对formGroupName的引用在ngFor循环之外,所以对所述formGroupName名称保持不变。

最新更新