【问题标题】:Angular FormAray of compnent组件的 Angular FormArray
【发布时间】:2021-06-15 11:48:39
【问题描述】:

我正在尝试做一个子组件反应形式的数组。每次我在子级(questionForm)中编辑时,它都会在父级(adminForm)中更新,我已经尝试这样做了 2 周。所以请如果你能帮助我感谢它我留下了一些我一直在做的相关代码

父.ts

 this.adminForm=this.fb.group({
      //SurveyName:this.nameForm.getData(),
      Questions: this.fb.array([
      ])
    });

get questions() {
    return this.adminForm.controls["Questions"] as FormArray;
  }
addQuestion() {
    //this.questions.push();
  }

父.html

<div *ngFor="let alias of questions.controls; let i=index">
            <app-question></app-question>
</div>
 <a (click)="addQuestion()">Add question</a>

child.ts

this.questionForm = this.fb.group({
      question: [''],
      type: ['Checkboxes'],
      required: [false],
      options: this.fb.array([
        this.fb.control('')
      ])
    });

【问题讨论】:

  • 能否请您在stackbliz中进行模拟,以便帮助您。

标签: angular angular-reactive-forms formarray angular2-formbuilder angular-formbuilder


【解决方案1】:

当你使用一个child来控制一个FormGroup时,有两种方法:

  1. 在父级中创建 formGroup 并使用@Input 传递给子级
  2. 在 child 中创建 formGroup 并使用 @Output 传递给 parent

对我来说使用第一种方法更舒服

如果你有你的父母

getGroup(){
  return this.fb.group({
      question: [''],
      type: ['Checkboxes'],
      required: [false],
      options: this.fb.array([
        this.fb.control('')
      ])
    });
}
//when add a question, always in parent
addQuestion() {
  this.questions.push(this.getGroup());
}

你的孩子只是有

formGroup:FormGroup;
@Input('form') set form(value){
    this.formGroup=value as FormGroup
}

hml 就像另一个 formGroup

   <form [formGroup]="formGroup">
     <input formControlName="question">
     ....
   </form>

你在父母中使用:

<div *ngFor="let alias of questions.controls; let i=index">
     <app-question [form]=questions.at(i)></app-question>
</div>

【讨论】:

    猜你喜欢
    • 2017-11-16
    • 2019-02-10
    • 2018-08-10
    • 2021-08-04
    • 2018-07-15
    • 1970-01-01
    • 1970-01-01
    • 2018-12-22
    • 2020-06-30
    相关资源
    最近更新 更多