【问题标题】:Ionic2 / Angular2 Forms With FormGroup For Nested Components用于嵌套组件的带有 FormGroup 的 Ionic2 / Angular2 表单
【发布时间】:2017-05-04 22:14:37
【问题描述】:

Ionic2 / Angular2 中,我很难让FormGroupFormGroupName 使用嵌套的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 中创建FormGroupFormControl 项。

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 类将 fieldformGroup 定义为输入。

@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


    【解决方案1】:

    好的,我发现了问题,所以分享解决方案以防它帮助其他人。

    看起来问题与[formControlName]="latitude" 上的绑定有关。

    <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>
    

    但它应该只是formControlName="latitude"

    <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>
    

    进行此更改后,嵌套的Component 按预期工作。希望这对其他人有帮助!

    【讨论】:

      猜你喜欢
      • 2017-09-16
      • 2017-06-11
      • 1970-01-01
      • 2017-03-25
      • 1970-01-01
      • 2018-08-06
      • 2017-01-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多