2017-09-12 27 views
7

我是从这个链接http://plnkr.co/edit/yV94ZjypwBgHAlb0RLK2?p=preview但得到推动和控制错误执行的代码。角4:房产“推”和“控制”上不存在型“AbstractControl”

这里是我做了什么,不知道什么是错的。

import { Component } from '@angular/core'; 
import { ViewController,Platform } from 'ionic-angular'; 
import { FormBuilder,FormGroup,Validators,FormControl,FormArray } from '@angular/forms'; 

@Component({ 
    selector: 'filter-vendor', 
    templateUrl: 'filter-vendor.html' 
}) 

export class FilterVendorPage { 




    questions = [{id:1,text:'Question 1', answers:[{id:1},{id:2}]},{id:2,text:'Question 2', answers:[{id:11},{id:22}]}] 
    surveyForm:FormGroup; 



    constructor(
    private viewCtrl: ViewController, 
    private formBuilder:FormBuilder 
    ){ 


     this.surveyForm=this.formBuilder.group({ 
     question:formBuilder.array([]) 
     }) 

     for(var i=0;i<this.questions.length;i++){ 
      let question=formBuilder.group({ 
      question_id:[this.questions[i].id,Validators.required], 
      answer_id:formBuilder.array([]) 
      }); 
      this.surveyForm.controls['questions'].push(question); 
     } 
} 


    onChange(id, isChecked, index) { 

    const answers = <FormArray>this.surveyForm.controls.questions.controls[index].controls.answer_ids 

    if(isChecked) { 
      answers.push(new FormControl(id)) 
     } else { 
      let idx = answers.controls.findIndex(x => x.value == id) 
      answers.removeAt(idx) 
    } 
    } 

} 

请帮我解决谢谢

回答

15

打字稿的类型检查抱怨这个issue.Lot的。你需要把你的控制权转移到FormArray。因此,改变

1)

this.surveyForm.controls['questions'].push(question); 

(<FormArray>this.surveyForm.controls['questions']).push(question); 

(this.surveyForm.controls['questions'] as FormArray).push(question); 

(this.surveyForm.get('questions') as FormArray).push(question); 

2)

const answers = <FormArray>this.surveyForm.controls.questions.controls[index].controls.answer_ids 

const answers = this.surveyForm.get(['questions', index, 'answer_ids']) as FormArray; 

const answers = this.surveyForm.get(`questions.${index}.answer_ids`) as FormArray; 

Forked Plunker

+0

的很多的感谢你从我的心脏底部。你救了我的命。 –

+0

我在findIndex收到错误让IDX = answers.controls.findIndex(X => x.value == ID) answers.removeAt(IDX)我不知道是什么毛病,因为它在plunker做工精细。 –

相关问题