Я пытаюсь создать formGroup, которая динамически добавляет больше formGroups, в которых одно из двух установленных свойств является массивом.Это вывод, который я хотел бы получить
{ 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)
Спасибо за вашу помощь, ребята.