首页 > 解决方案 > 如何在 Angular 11 中创建嵌套表单数组

问题描述

我正在尝试在角度 11 中嵌套表单数组。截至目前,我已经尝试过这样的操作,并且工作正常。


spinner: boolean = false;
  new_created: boolean = true;
  create_question_form: FormGroup;
  group: any = new FormGroup({
    name: new FormControl(''),
  });

  constructor(private route: ActivatedRoute, private fb: FormBuilder) {}

  validation() {
    this.create_question_form = this.fb.group({
      question: new FormArray([this.group]),
    });
  }

  get question() {
    return this.create_question_form.get('question') as FormArray;
  }

  add_question() {
    this.question.push(this.group);
  }

  create_question() {
    const data = this.create_question_form.getRawValue();
    console.log(data);
  }

  ngOnInit(): void {
    this.validation();
    this.add_question();
  }
 <form
            [formGroup]="create_question_form"
            (ngSubmit)="create_question()"
          >
            <ng-container formArrayName="question">
              <div *ngFor="let _ of question.controls; index as i">
                <ng-container [formGroupName]="i">
                  <div class="col-12 col-md-4 mt-5">
                    <span class="p-float-label w-100">
                      <input
                        type="text"
                        id="inputtext"
                        class="form-control"
                        formControlName="name"
                        pInputText
                      />
                      <label for="inputtext">Name</label>
                    </span>
                  </div>
                </ng-container>
              </div>
            </ng-container>

            <button type="submit" class="btn btn-success">Create</button>
          </form>

但我想要的是在我的 Formgroup 中创建一个新的 FormArray (Address),就像这样。

 group: any = new FormGroup({
    name: new FormControl(''),
    address:new FormArray([]),
  });

我不知道如何在我的 HTML 中访问这个地址表单数组,或者如何在这个数组中推送新的 FormControl。

标签: angulartypescriptangular-reactive-forms

解决方案


添加新组: this.group.controls.address.push(new FormGroup({street: new FormControl('')}));

用于访问该添加的组: this.group.controls.address['controls'][0]['controls']['street'].value

删除该组: let group_arr = (this.group.controls.address as FormArray); group_arr.removeAt(index)


推荐阅读