Angular FormArray推送表单组

时间:2019-06-10 06:45:17

标签: angular forms typescript angular-reactive-forms

每次尝试这样的操作时,都会向我显示错误“ TypeError:control.setParent不是函数”。目标是获取答案(“ odgovori” FormArray),但不要在输入中循环,而要在单选组中循环。 ..而不是用户选择单选按钮作为正确答案并存储所有内容。何时做:

console.log(this.odgovorForm.value)

一切正常,但是当按下时显示错误

get odgovori() {
    return this.pitanjeForm.get('odgovori') as FormArray;
  }

 pitanjeForm = this.fb.group({
    data: ['', [Validators.required]],
    odgovori: this.fb.array([]),
    tacan: ['', [Validators.required]]
  });

  odgovorForm = this.fb.group({
    data: ['', [Validators.required]],
    color: 'danger'
  });

  addAnswer(): void {
    console.log(this.pitanjeForm.value, this.odgovorForm.value);
    this.info = this.odgovorForm.value;
    this.odgovori.push(this.info);
  }

HTML

<form [formGroup]="pitanjeForm">
 <div>
   <input formControlName="data">
 </div>
  <form [formGroup]="odgovorForm">
    <input formControlName="data">
    <button (click)="addAnswer()"></button>
  </form>
 <div *ngFor="let odgovor of odgovor.value; index as i">
   <input type="radio" value="{{ i }}"> 0 - 30<br>
 </div>
</form>

4 个答案:

答案 0 :(得分:1)

我把代码像Er Abdul Meman一样,但是我得到了 类型上不存在属性推送错误。

enter image description here

这对我有用:

import { OnInit } from "@angular/core";
import { FormBuilder,Validators } from "@angular/forms";

export class YourClass implements OnInit {
  pitanjeForm = this.fb.group({
    articulo_alquiler: this.fb.array([]),
  });

  odgovorForm = this.fb.group({
    name: [null],
    quantity: [0, Validators.compose([Validators.required, Validators.min(0)])],
    total: 0,
  });

  constructor(private fb: FormBuilder) {}

  get articulo_alquiler() {
    return this.pitanjeForm.get("articulo_alquiler") as FormArray;
  }

  addArticulo(): void {        
    this.articulo_alquiler.push(this.odgovorForm);
    // console.log(this.articulo_alquiler);
    // console.log(this.pitanjeForm.value.articulo_alquiler);
  }
}

答案 1 :(得分:1)

尝试将public odgovori = this.pitanjeForm.get('odgovori')用作FormArray。 然后angular知道了它是一个数组,您可以向其中推入一些东西。

答案 2 :(得分:0)

用下面的代码替换您的代码

    public odgovori = this.pitanjeForm.controls['odgovori'];


 pitanjeForm = this.fb.group({
    data: ['', [Validators.required]],
    odgovori: this.fb.array([]),
    tacan: ['', [Validators.required]]
  });

  odgovorForm = this.fb.group({
    data: ['', [Validators.required]],
    color: 'danger'
  });

  addAnswer(): void {
    console.log(this.pitanjeForm.value, this.odgovorForm.value);
    this.info = this.odgovorForm.value;
    this.odgovori.push(this.info);
    console.log(this.odgovori)
  }

答案 3 :(得分:0)

哦..我的错误

addAnswer(): void {
 this.odgovori.push(this.odgovorForm)
}

推送表单以形成阵列,始终推送整个表单,而不仅仅是价值或控制!