Angular 5 formBuilder - 嵌套数组和 For 循环

Angular 5 formBuilder - Nested Array and For loop

我在 ionic 应用程序的个人资料编辑页面上工作,所有用户个人资料信息的顶级项目(姓名、电子邮件、性别等)一切正常。

我的爱好存储在这个主 json 节点(使用 Firestore)之外的数组中,所以它在主节点之外的第 1 层深处..

我似乎不知道如何使用表单生成器。我怀疑我在 2 点上出错了,1 是我使用 formbuilder 的方式,2 是关于合并功能,因为它没有考虑嵌套结构,我也不确定如何处理。任何帮助都会很棒。

  _buildForm() {

    this.form = this.formBuilder.group({
      displayName: [this.options.displayName] || '',
      dob: [this.options.dob] || '',
      sex: [this.options.sex] || '',
      city: [this.options.city] || '',
      country: [this.options.country] || '', 
      bio: [this.options.bio] || '',   
      hobbies: this.formBuilder.group( this.options.hobbies )  
    });

    // Watch the form for changes, and
    this.form.valueChanges.subscribe((v) => {
      this.merge(this.form.value);
    });
  }  


  merge(settings: any) {

    for (let k in settings) {
      this.settings[k] = settings[k];
    }
    return this._save();
  }


  _save() {
     // this function then save the data back to firestore using a simple update of the entire json output
  }

你需要这些

 _buildForm() {
    this.form = this.formBuilder.group({
      displayName: [this.options.displayName] || '',
      dob: [this.options.dob] || '',
      sex: [this.options.sex] || '',
      city: [this.options.city] || '',
      country: [this.options.country] || '', 
      bio: [this.options.bio] || '',   
      hobbies: this.formBuilder.group([])  
    });
    if(this.options.hobbies.length>0){
      this._setHobbiesForm(this.options.hobbies);
    }
  }  

  //To build the hobby gorm
  _buildHobbyForm(hobby) {
    var hobbyForm = this.fb.group({
      Name: hobby.Name||''
    });
    return hobbyForm ;
  }

  //To attach the hobbies form with data back to main form
  _setHobbiesForm(hobbies) {
    const hobbiesFGs = hobbies.map(hobby=> this._buildHobbyForm(hobby));
    const hobbiesFR = this.fb.array(hobbiesFGs);
    this.form.setControl('hobbies', hobbiesFR);
  }

 //To get form values for saving
 _prepareSaveInfo(){
    const formModel = this.form.value;
    //deep copy of hobbies
    const hobbiesDeepCopy= formModel.hobbies.map(
      (hobby) => Object.assign({}, hobby)
    );
    const profile={
      displayName: formModel.displayName as string,
      sex: formModel.sex as string,
      dob: formModel.dob as string,
      city: formModel.city as string,
      country: formModel.country as string,
      hobbies:hobbiesDeepCopy
    }
    return profile;
  }

  _save() {
    let dataToSave=this._prepareSaveInfo();
    console.log(dataToSave);
  }

这是在angular中处理表单内数组的方法,如果它不完全符合您的代码逻辑,请以它为例并从中构建您的逻辑,绝对这个例子会帮助你。

我也在此处发布 html 的示例(主要是为了展示如何处理 html 中表单内的数组)

<div formArrayName="hobbies">
    <div *ngFor="let hobby of form.get('hobbies').controls; let i=index" [formGroupName]="i">
    <!-- your code for hobby-->
    </div>
</div>