I am trying to push new controls dynamically into my formBuilder.
/* templatesTypes = ["string1", "string2", "string3","string4"] */
/* templates = [{templateType: "string1", ...}, {templateType: "string2"}, ...]*/
this.agency = this.fb.group({
name: [],
templates: this.fb.array([])
});
const arrayControl = this.agency.controls['templates'] as FormArray;
const objControl = {};
templatesTypes.forEach(templateType => {
objControl[templateType] = [{
value: templates.filter(template => template.templateType === templateType)
}];
arrayControl.push(this.fb.group(objControl));
});
<div formArrayName="templates" *ngFor="let templateType of agency.get('templates').controls; let i = index">
<div [formGroupName]="i">
<label>{{ templateType.name }}</label>
<ng-select
[items]="agency.get('templates').controls[i]"
bindLabel="templateName"
formControlName="{{ templateType.name }}">
</ng-select>
</div>
</div>
The control name is dynamic, based on the template name ("string1", "string2", ...).
But I don't found any way to get the control name dynamicaly. I try with templateType.name
but it's return nothing.
The templateType
in HTML template is instanced of AbstractControl
which does not have name
property.
I think this code should work fine.
<div formArrayName="templates" *ngFor="let templateType of agency.get('templates').controls; let i = index">
<div [formGroupName]="i">
<label>{{ templateType.name }}</label>
<ng-select
[items]="agency.get('templates').controls[i]"
bindLabel="templateName"
formControlName="{{ templates[i].templateType }}">
</ng-select>
</div>
</div>
Reference:
- AbstractControl
: https://angular.io/api/forms/AbstractControl