角度4:将属性“推"为和“控件"在类型"AbstractControl"上不存在 [英] Angular 4: Property "push" and "controls" does not exist on type "AbstractControl"
本文介绍了角度4:将属性“推"为和“控件"在类型"AbstractControl"上不存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已通过此链接实现了代码 http://plnkr.co/edit/yV94ZjypwBgHAlb0RLK2? p = preview ,但出现推送并控制错误.
I was implemented the code from this link http://plnkr.co/edit/yV94ZjypwBgHAlb0RLK2?p=preview but getting push and controls error.
这是我所做的,并且不知道这是怎么回事.
Here is what i did and don't know what is wrong with it.
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)
}
}
}
请帮助我解决此问题.非常感谢
Please help me to resolve this issue.Lot's of thanks
推荐答案
Typescript抱怨类型检查.您需要将控件转换为FormArray
.所以改变
Typescript complains on type checking. You need to cast your control to FormArray
. So change
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
这篇关于角度4:将属性“推"为和“控件"在类型"AbstractControl"上不存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文