【发布时间】:2017-05-04 22:14:37
【问题描述】:
在Ionic2 / Angular2 中,我很难让FormGroup 和FormGroupName 使用嵌套的Components,不断收到类似的错误。
Cannot find control with path: 'location -> latitude'
Form 页面呈现动态的字段列表。
<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>
Form 类在ionViewDidLoad 中创建FormGroup 和FormControl 项。
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(''));
}
}
Location 类将 field 和 formGroup 定义为输入。
@Component({
selector: 'field-location',
templateUrl: 'location.html',
inputs: ['field', 'formGroup']
})
export class LocationComponent {
field: any = {};
formGroup: FormGroup;
constructor() {
}
}
Location 视图将FormGroup 用作Input,并将Key 字段用作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>
如何让formGroupName 在嵌套的Components 中工作?您还需要从父级传递嵌套的FormGroup 吗?
【问题讨论】:
标签: ionic2 angular2-forms