Reputation: 9790
I'm using Angular 6
. and Reactive form builder
to build a form.
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: [],
});
}
}
I have to prefill few fields initially and faqs
is an array field in which new fields are generated dynamically by calling
onClickAddFaqField(): void {
this.faqFields = this.landingPageForm.get('faqs') as FormArray;
this.faqFields.push(this.createFaqFields());
}
Initially, there is only one faq input field in HTML and that empty. But it is giving an error
"Must supply a value for form control at index: 0.
How can I initialize the array input field empty?
Upvotes: 0
Views: 7172
Reputation: 9790
After trying all the answers and examples from different sources. This is how I solved it.
private _setFormValue() {
if (this.product) {
this.landingPageForm.setValue({
title: this.product.info.title,
description: '',
faqs: [{
question: '',
answer: ''
}],
});
}
}
Added question, answer
with empty value as the first object to the faqs
field.
Upvotes: 0
Reputation: 310
Instead of using FormControl() in createFaqFields(), try like this,
ngOnInit() {
this.landingPageForm = this.formBuilder.group({
title:'',
description: '',
faqs: this.formBuilder.array([this.createFaqFields()])
});
this._setFormValue();
}
createFaqFields(): FormGroup {
return this.formBuilder.group({
question: '',
answer: ''
});
}
Upvotes: 0
Reputation: 4039
I guess, I would do this:
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)
});
}
Upvotes: 1