I am currently working on a feature where I need to dynamically add new controls to 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 naming of the control is based on the dynamic template name ("string1", "string2", ...).
However, I am facing challenges in retrieving the control name dynamically. I have tried using templateType.name
, but it does not seem to return anything.