如何在Angular 2/4/5 FormArray中对子组

时间:2018-04-20 18:32:11

标签: angular

我有表格

this.form = this.fb.group({
  displayName: [user.displayName, Validators.required],
  profile: this.fb.group({
    gender: [user.profile.gender, Validators.required],
    birthday: [user.profile.birthday, Validators.required],
    place_of_birth: [user.profile.place_of_birth, Validators.required],
    place_of_residence: [user.profile.place_of_residence, Validators.required],
    about_me: [user.profile.about_me, Validators.required],
    interests: [user.profile.interests, Validators.required],
    sport: [user.profile.sport, Validators.required],
    highSchool: this.fb.array(educationFGs)
  })
});

highSchool是一个群组中的项目"个人资料"来自一个小组。

我只需更新highSchool;

在我做之前:

this.educations.splice(index, 1);
const educationFGs = this.educations.map(education => this.fb.group(education));
const educationArray = this.fb.array(educationFGs);

this.form.setControl('highSchool', educationArray);

但是我在一个小组中移动highSchool后,我不知道如何访问它。

这对我不起作用:

this.form.setControl('profile.highSchool', educationArray);

1 个答案:

答案 0 :(得分:0)

解决方案是通过get和push new val

访问Form Control
add() {
    const fa = this.form.get('profile.highSchool') as FormArray;
    fa.push(this.fb.group({
      name: '',
      date: ''
    }));
  }

要删除项目,请使用removeAt

remove(index) {
  const fa = this.form.get('profile.highSchool') as FormArray;
  fa.removeAt(index);
}