2016-12-16 21 views
2

为什么我一直得到这个错误?我认为我做的一切都对吗?FormArray TypeError:value.forEach不是函数

“例外:未捕获(在承诺):类型错误:value.forEach不是函数 类型错误:value.forEach不在FormArray.setValue一个函数”

组件类:

jobDetails: FormGroup; 
techFormArray: FormArray; 

constructor(private formBuilder: FormBuilder){ 

    this.techFormArray = new FormArray([ 
     new FormControl(''), 
     new FormControl(''), 
     new FormControl('') 
    ]); 
    this.jobDetails = this.formBuilder.group({ 
     techs: this.formBuilder.array([]) 
    }); 
    this.jobDetails.setValue({ 
     techs: this.techFormArray 
    }); 
} 

HTML:

<form [formGroup]="jobDetails"> 
    <div formArrayName="techs" > 
    <div style="display: flex; flex-direction: column"> 
     <div *ngFor="let tech of techFormArray.controls; let i=index"> 
     <md-checkbox [formControlName]="i"> 
      {{i}} 
     </md-checkbox> 
     </div> 
    </div> 
    </div> 
</form> 

SOLUTION:

FunStuff有正确的,我不能使用setValue ....所以我删除它。问题解决了哈哈。我改变了几件事情,我不确定我做了什么,它几乎是几个小时的暴力试验和错误,但后来它工作! :)

这是工作版本!

jobDetails: FormGroup; 

constructor(private formBuilder: FormBuilder){ 

    this.jobDetails = formBuilder.group({ 
     techs: formBuilder.array([ 
      formBuilder.control(''), 
      formBuilder.control('') 
     ]) 
    }); 
} 

新的HTML:

<form [formGroup]="jobDetails"> 
     <div formArrayName="techs" > 
      <div style="display: flex; flex-direction: column"> 
       <div *ngFor="let tech of jobDetails.controls.techs.controls; let i=index"> 
        <md-checkbox [formControlName]="i"> 
         {{i}} 
        </md-checkbox> 
       </div> 
      </div> 
     </div> 
    </form> 
+0

分别是代码中的每个功能..一些,你试图控制.value.foreach funtion – mayur

+0

这样的东西: - 'this.techFormArray.value.forEach(()=> {/ ** /}' – mayur

+0

这是导致错误的组件。没有告诉它使用循环,但我认为FunStuff的答案可能是为什么。我今天会看看。 – Jus10

回答

5

的setValue方法只接受简单的价值观:

this.techFormArray = new FormArray([ 
     new FormControl(''), 
     new FormControl(''), 
     new FormControl('') 
    ]); 

    this.jobDetails = this.formBuilder.group({ 
     techs: this.techFormArray 
    }); 

    this.jobDetails.setValue({ 
     techs: ['a', 'b', 'c'] 
    }); 
+0

对不起,我不认为它很重要,所以我没有包括它,但在这种情况下,我扔了三个模拟值,实际上我实际上并不知道这些值。我想根据需要将它们推入阵列中。如果我们不知道数组的大小,我们如何设置值? – Jus10

+0

只需推新的FormControl。 this.techFormArray.push(新的FormControl('')) – Bazinga

+0

@FunStuff你可以解释一下,this.techFormArray.push(新的FormControl('')) –