我对Angular非常陌生,但是在我来到这里之前,我尝试了很多搜索以找到解决方案。我的问题:使用模板方法,我尝试创建一个嵌套表单,其中还包含子组件的输入字段。为了使子组件在父表单对象中注册,我在子组件中添加了:
viewProviders: [ { provide: ControlContainer, useExisting: NgForm }
它工作正常,现在子组件输入已集成到父表单对象中。但是,子组件被多次引用,因此子组件的字段集应多次集成到formobject中。相反,子组件的输入字段仅添加一次。我认为这是因为输入字段需要唯一的名称,否则它们将被覆盖,或者?为了进一步说明,我使用ngFor遍历了一个配置文件,该文件包含以下信息:子组件需要多长时间被加载到父模板中。这是我在配置文件上循环的父组件的模板。我用Angular Bootstrap创建一个手风琴:
parent.html
<form (ngSubmit)="onSubmitJob()" #f="ngForm">
<div class="form-group">
<div *ngFor="let process of processMappings">
<div *ngIf="process.processId === selectedProcessingTool">
<div *ngFor="let input of process.inputs; let i = index">
<ngb-accordion
#acc="ngbAccordion"
activeIds="ngb-panel-0"
>
<ngb-panel title="{{ input.inputType }}">
<ng-template ngbPanelContent>
<child-component
*ngIf="
input.inputType == 'StaticSubsetDefinition';
"
></child-component>
</ng-template>
</ngb-panel>
</ngb-accordion>
</div>
</div>
</div>
</div>
</form>
这是子组件的模板,其中包括一个字段集:
child.html
<fieldset ngModelGroup= "staticSubsetDefinition">
<div class="form-group">
<label for="value">Wert</label>
<input
style="max-width: 300px;"
class="form-control"
id="value"
placeholder=""
ngModel
name = "value"
required
/>
</div>
<div class="form-group">
<label class="my-1 mr-2" for="dataType">Datentyp</label>
<select
class="form-control"
id="dataType"
style="max-width: 300px;"
ngModel
name="dataType"
required
>
<option selected></option>
<option value="text">Text</option>
<option value="numeric">numerisch</option>
</select>
</div>
</fieldset>
父项的模板会创建一个具有两个面板的风琴,因为子级会被两次加载到模板中。但是,formobject只注册一个,而我猜这是因为输入需要唯一的名称。因此,我的问题是,我该怎么做才能更改输入字段的名称,例如通过将索引添加到字段集名称?我不知道如何将索引添加到子组件的输入名称,例如在for循环中。这个怎么做?还是有另一种方式告诉Angular添加加载到模板的频率?
我的意思是在星星之间这样的东西(我想这是错误的,只是为了让您了解我的意思):
<div *ngFor="let input of process.inputs; let i = index">
<ngb-accordion
#acc="ngbAccordion"
activeIds="ngb-panel-0"
>
<ngb-panel title="{{ input.inputType }}">
<ng-template ngbPanelContent>
<child-component
*ngIf="
input.inputType == 'StaticSubsetDefinition';
" **inputname == 'inputname_ + i'**
></child-component>
</ng-template>
</ngb-panel>
</ngb-accordion>
</div>
本质上,我不知道如何从父组件的模板访问输入字段名称。但是,如果有将组件字段添加到forminput的其他方法,我很乐意在此代码中执行此操作。
我确实找到了自己的解决方案,并且正如我期望的那样,这只是一个简单的解决方案,只需使用Angulars Input指令即可:我只需要向子组件添加Input,定义一个变量即可从父模板接收值,并使用值(此处为索引)通过字符串插值来更改子组件中字段集的名称:
child.ts
import { Input} from '@angular/core';
...
@Input() index: number;
在子模板中,我使用字符串插值更改了字段集名称:
child.html
<fieldset ngModelGroup= "staticSubsetDefinition_{{index}}">
然后通过使用属性绑定[index] = i
从父模板中获取索引变量的值:
parent.html
<div *ngFor="let input of process.inputs; let i = index">
<ngb-accordion
[closeOthers]="true"
#acc="ngbAccordion"
activeIds="ngb-panel-0"
>
<ngb-panel title="{{ input.inputType }}">
<ng-template ngbPanelContent>
<child-component [index]="i"
*ngIf="
input.inputType == 'StaticSubsetDefinition';
"
></child-component>
</ng-template>
</ngb-panel>
</ngb-accordion>
</div>