I am trying to implement an edit form for a model with nested attributes (FormArray). I have syntax problems, and I'm not sure if I'm on the right track. Attributes for the main form work, this is a nested form that I'm having problems with. Here is what I still have.
Here I start a group of forms:
private initForm() { this.subscription = this.expenseService.getExpense(this.id) .subscribe( expense => { this.expense = expense; this.patchForm(); } ); this.expenseEditForm = this.fb.group({ date: '', amount: '', check_number: '', debit: '', payee_id: '', notes: '', expense_expense_categories_attributes:[] }); }
Here I correct the form for setting values ββfrom an object obtained from my API.
private patchForm() { this.expenseEditForm.setValue({ date: '', amount: this.expense.amount_cents, check_number: this.expense.check_number, debit: this.expense.debit, payee_id: '', notes: this.expense.notes, expense_expense_categories_attributes: this.fb.array([ this.setExpenseCategories(), ]) }); }
This is where I am stuck. How I click on FormArray. If I try to click, I get an error that it does not exist in FormArray.
private setExpenseCategories() { for ( let expenseCategories of this.expense.expense_expense_categories){ this.fb.array.push([ this.fb.group({ expense_category_id: [expenseCategories.expense_category_id, Validators.required], amount: [expenseCategories.amount_cents] ]) }); } }
Just in case, this is necessary. Here is my html.
<div *ngFor="let expensecategoriesCtl of expenseEditForm.controls.expense_expense_categories_attributes.controls let i = index" [formGroupName]="i" style="margin-top: 10px;"> <md-card> <md-select class="full-width-input" placeholder="Expense Category" id="expense_category_id" formControlName="expense_category_id" > <md-option *ngFor="let expenseCategory of expenseCategories" value="{{expenseCategory.id}}"> {{expenseCategory.category}} </md-option> </md-select> <md-input-container class="full-width-input"> <input mdInput placeholder="Amount" type="number" formControlName="amount"> </md-input-container> </md-card> </div>