In Ionic2 / Angular2, I'm struggling to get FormGroup and FormGroupName working with nested Components, keep getting errors like.
Cannot find control with path: 'location -> latitude'
The Form page renders a dynamic list of fields.
<form [formGroup]="formGroup" (ngSubmit)="postForm()">
<ion-list>
<ion-item *ngFor="let field of fields">
<field-location [field]="field" [formGroup]="formGroup" *ngIf="field.input == 'location'"></field-location>
<!-- OTHER FIELD TYPES HERE -->
</ion-item>
</ion-list>
</form>
The Form class creates the FormGroup and FormControl items in ionViewDidLoad.
this.formGroup = new FormGroup({});
for (let index in this.fields) {
let field = this.fields[index];
if (field.input == 'location') {
this.formGroup.addControl(field.key, new FormGroup({
latitude: new FormControl(''),
longitude: new FormControl('')}));
}
else {
this.formGroup.addControl(attribute.key, new FormControl(''));
}
}
The Location class defines field and formGroup as inputs.
@Component({
selector: 'field-location',
templateUrl: 'location.html',
inputs: ['field', 'formGroup']
})
export class LocationComponent {
field: any = {};
formGroup: FormGroup;
constructor() {
}
}
The Location view takes the FormGroup as an Input and uses the field Key as the formGroupName.
<ion-item [formGroup]="formGroup" *ngIf="formGroup">
<ion-label>{{field.label}}</ion-label>
<div [formGroupName]="field.key">
<ion-input type="text" hidden [formControlName]="latitude"></ion-input>
<ion-input type="text" hidden [formControlName]="longitude"></ion-input>
</div>
</ion-item>
How do you get formGroupName to work in nested Components? To you need to also pass the nested FormGroup in from the parent?
Ok, I found the problem, so sharing the solution in case it helps others.
Looks like the issue was related to binding on
[formControlName]="latitude".But it should just have been
formControlName="latitude".After making this change, the nested
Componentworks as expected. Hope this helps someone else!