我正在使用Angular 6
。和Reactive form builder
建立表单。
ngOnInit() {
this.landingPageForm = this.formBuilder.group({
title: new FormControl('', [
Validators.required
]),
description: new FormControl('', [
Validators.required
]),
faqs: this.formBuilder.array([
this.createFaqFields()
]),
});
this._setFormValue();
}
createFaqFields(): FormGroup {
return this.formBuilder.group({
question: new FormControl(),
answer: new FormControl()
});
}
private _setFormValue() {
if (this.product) {
this.landingPageForm.setValue({
title: this.product.info.title,
description: '',
faqs: [],
});
}
}
我必须在开始时预填充几个字段,faqs
是一个数组字段,在其中通过调用
onClickAddFaqField(): void {
this.faqFields = this.landingPageForm.get('faqs') as FormArray;
this.faqFields.push(this.createFaqFields());
}
最初,HTML中只有一个常见问题输入字段,并且为空。但这是一个错误
"Must supply a value for form control at index: 0.
如何将数组输入字段初始化为空?
答案 0 :(得分:0)
我想我会这样做:
ngOnInit() {
this.landingPageForm = this.formBuilder.group({
title: new FormControl('', [Validators.required]),
description: new FormControl('', [Validators.required]),
faqs: this.formBuilder.array([])
});
// Try this
// OTOH why when you set that to [] in _setFormValue()?
this.landingPageForm.get('faqs').push(this.createFaqFields());
this._setFormValue();
}
createFaqFields(): FormGroup {
return new FormGroup({
question: new FormControl(null),
answer: new FormControl(null)
});
}
答案 1 :(得分:0)
代替在createFaqFields()中使用FormControl(),尝试这样,
ngOnInit() {
this.landingPageForm = this.formBuilder.group({
title:'',
description: '',
faqs: this.formBuilder.array([this.createFaqFields()])
});
this._setFormValue();
}
createFaqFields(): FormGroup {
return this.formBuilder.group({
question: '',
answer: ''
});
}
答案 2 :(得分:0)
尝试了不同来源的所有答案和示例后。这就是我解决的方法。
private _setFormValue() {
if (this.product) {
this.landingPageForm.setValue({
title: this.product.info.title,
description: '',
faqs: [{
question: '',
answer: ''
}],
});
}
}
在第question, answer
字段中添加了faqs
(空值)作为第一个对象。