0

我正在尝试创建一个动态添加更多 formGroups 的 formGroup,其中 2 个属性集之一是数组。这是我想要的输出

{ entity_0: {
    entity: 'whatever',
    values: ['value1', 'value2', 'value3']
}, { entity_1: {
    entity: 'whatever',
    values: ['value1', 'value2', 'value3']
}

这就是我在我的 ts 文件中为动态创建 formGroup 所做的:

createNewEntity() {
    this.entities.push({ entity: 'entity', values: [] }); //just pushing a random value to array in order to populate the html list
    this.currentIndex = this.entities.length - 1;

    this.entitiesForm.addControl(`entity_${this.currentIndex.toString()}`, this.fBuilder.group({
      'entity':new FormControl(" ", Validators.required),
      'values': new FormArray([])
    }));

addValue() {
    this.entities[this.currentIndex].values.push('value'); //just pushing a random value to array in order to populate the html list
 //then how to retrieve the new formgroup and update the array with each value?
}

这是html文件:

<ul>
    <li *ngFor="let entity of entities; let i = index">
        <label>Insert entity name</label>
        <div >
                <input formControlName=entity_{{i}}>
        </div>

        <button (click)="addValue()">Add Value</button>
        <ul>
            <!--go through the array values in the entity object and display as many inputs as needed-->
            <li *ngFor="let value of entity.values; let j = index">
                <input placeholder="insert value" formControlName=value_{{j}} >
            </li>
        </ul>
    </li>
</ul>
<button (click)="createNewEntity()">Add Intent</button>

我似乎无法让它工作,至少无法创建新的 FormGroup。我在控制台中收到此错误:

ERROR Error: Cannot find control with name: 'entity'
at _throwError (forms.js:1732)
at setUpControl (forms.js:1640)
at FormGroupDirective.push../node_modules/@angular/forms/fesm5/forms.js.FormGroupDirective.addControl (forms.js:4454)
at FormControlName.push../node_modules/@angular/forms/fesm5/forms.js.FormControlName._setUpControl (forms.js:4959)
at FormControlName.push../node_modules/@angular/forms/fesm5/forms.js.FormControlName.ngOnChanges (forms.js:4909)
at checkAndUpdateDirectiveInline (core.js:9246)
at checkAndUpdateNodeInline (core.js:10514)
at checkAndUpdateNode (core.js:10476)
at debugCheckAndUpdateNode (core.js:11109)
at debugCheckDirectivesFn (core.js:11069)

谢谢你们的帮助。

4

0 回答 0