I am struggling with adding dynamic form controls on dropdown change. I have been able to add them, but encountered an error preventing me from retrieving the value in 'formName.value'.
The specific error message states: "Error: There is no FormControl instance attached to form control element with name: 'countryName'".
Here is my code:
ngOnInit(): void {
this.getFormControlsFields(Object.keys(this.countryKey)[0]);
}
getFormControlsFields(field: string) {
const formGroupFields: any = {};
formGroupFields[field] = new FormControl('');
this.formFields.indexOf(field) === -1 && this.formFields.push(field);
this.contactForm = new FormGroup(formGroupFields);
}
handleChange(value: any, type: string) {
if (type === 'countryName') {
this.getFormControlsFields(Object.keys(this.countryKey.states.s1)[0]);
this.removeFormControls(['districtName', 'placeName']);
this.fieldValues = {
...this.fieldValues,
stateName: this.getFilteredList(secondLevelArr, value)
};
}
}
Below is the relevant HTML code:
<form [formGroup]="contactForm" (ngSubmit)="onSubmit()">
<div *ngFor="let field of formFields">
<mat-form-field *ngIf="field" appearance="fill" class="w-100-per">
<mat-label>{{field | titlecase}}</mat-label>
<mat-select [formControlName]="field" (selectionChange)="handleChange($event.value, field)">
<mat-option *ngFor="let value of fieldValues[field]" [value]="value.id">{{value.name}}</mat-option>
</mat-select>
</mat-form-field>
</div>
<button type="submit" mat-raised-button color="primary">Submit</button>
</form>