Issue
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?
Solution
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.
Answered By - Anuj TBE
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.