In my application, I have a table of cashflows where each cashFlow consists of a varying number of periods. When a cashflow is clicked, I am attempting to populate a component so that the period values can be edited. The cashflow name along with the start and end dates are automatically filled in. Additionally, there is an array of periods with text boxes displayed for each period.
Despite my efforts, I am facing difficulties in displaying the initial values in the textboxes.
I have tried using patchValue or setValue methods without success.
I have meticulously gone through 12 related questions on Stack Overflow for guidance. While one suggestion gave me an idea to test, it did not provide a solution to my issue.
Below is the code snippet from cashFlowDetailComponent.ts:
// Angular imports
import { Component, OnInit , Input, Output, ElementRef} from '@angular/core';
import { ReactiveFormsModule, FormBuilder, FormGroup, FormArray, FormControl, ValidatorFn } from '@angular/forms';
import {cashFlow, cashFlowPeriod} from '../cashflow'
import { IMyDpOptions, IMyDateModel, IMyDate } from 'mydatepicker';
@Component({
selector: 'app-cashflow-detail',
templateUrl: './cashflow-detail.component.html',
styleUrls: ['./cashflow-detail.component.css']
})
export class CashflowDetailComponent implements OnInit {
// Properties declaration
myFormGroup: FormGroup;
myCashFlow: cashFlow;
constructor(private fb: FormBuilder) {}
buildForm(cf_: cashFlow): void {
this.myFormGroup = null;
this.myCashFlow = cf_;
if (cf_ == null) { return; }
const a :FormArray = this.fb.array([]);
this.myCashFlow.periods.forEach(cfp => {
a.push(this.cfpGroup(cfp));
})
this.myFormGroup = this.fb.group({
cashFlowName: this.myCashFlow.cashFlowName,
startDate: this.threePartDateFromDate( this.myCashFlow.startDate),
endDate: this.threePartDateFromDate( this.myCashFlow.endDate),
periods:a
});
// Trying to set initial values in textboxes
this.myFormGroup.controls['periods'].controls[i].controls['value1'].setValue(this.myCashFlow.periods[i].value1);
}
cfpGroup(cfp_ : cashFlowPeriod) :FormGroup{
const g : FormGroup = this.fb.group({
value1: cfp_.value1
});
return g;
}
threePartDateFromDate(d_: string): any {
const date_ = new Date(d_);
return {
date: {
year: date_.getFullYear(),
month: date_.getMonth()+1,
day: date_.getDate()
}
};
}
}
Here is the template being used:
<div *ngIf="myCashFlow && myFormGroup" [formGroup]="myFormGroup">
<table style="margin:7px 7px 7px 7px">
<tr>
<td class="fieldLabel">Cash Flow Name</td>
<td>
<input type="text"
formControlName="cashFlowName"
style="width:175px;" />
</td>
</tr>
</table>
<table border="1">
<tr>
<td *ngFor="let cfp of myCashFlow.periods,let i=index">{{cfp.periodName}}</td>
</tr>
<tr>
<td *ngFor="let cfp of myCashFlow.periods, let i=index" style="padding:7px;">
<input type="text"
[id]="cfp.periodName"
style="width:35px;" />
</td>
</tr>
</table>
</div>