I'm trying to retrieve the values of dynamic inputs and to sum up them afterwards.
this is my html with the form and the stepper
<form
clrStepper
clrForm
#allocationForm="ngForm"
(ngSubmit)="submit(allocationForm.value)"
>
<clr-stepper-panel ngModelGroup="{{allocation.type}}" *ngFor="let allocation of allocations; let last = last" #{{allocation.type}}="ngModelGroup">
<clr-step-title>{{allocation.type}} </clr-step-title>
<clr-step-content *clrIfExpanded>
<p style=" margin-top: 24px">Der Gesamtbetrag muss 100% betragen.</p>
<div >
<div style="margin-top: 24px;">
<clr-input-container style="display: flex; flex-direction: row; min-height: 48px; margin-top: 8px;" *ngFor="let sub of allocation.subtype; let i = index" >
<label >{{sub.name}}</label>
<input name="{{'value' i}}" clrInput [min]="0" [max]="100"
clrNumeric pattern="^[0-9][0-9]?$|^100$" required [(ngModel)]="sub.value" clrUnit="%" value="{{sub.value}}"
>
<clr-control-error *clrIfError>0-100%</clr-control-error>
</clr-input-container>
</div>
</div>
<button clrStepButton="next" (click)="checkPercentage(allocationForm)" *ngIf="!last">WEITER</button>
<button clrStepButton="submit" *ngIf="last">SPEICHERN UND BEENDEN</button>
</clr-step-content>
</clr-stepper-panel>
</form>
in my ts file
allocationForm: NgForm;
allocations = [
{
type: 'Department',
subtype: [
{ name: 'AR', value: 0 },
{ name: 'SC ', value: 0 },
{ name: 'SCH ', value: 0 },
{ name: 'LAC ', value: 0 }
],
},
{
type: 'Groups',
subtype: [
{ name: 'LAC', value: 0 },
{ name: 'ME ', value: 0 },
{ name: 'RR ', value: 0 },
{ name: 'SP ', value: 0 }
],
}
{ }...
submit(allocationForm: {}) {
console.log(' form submit', Object.values(allocationForm));
for (let value of Object.values(allocationForm)) {
console.log(value)
}}
checkPercentage(allocationForm: NgForm) {
/*console.log(Object.values(allocationForm));
const sum = Object.values(allocationForm).reduce((acc, cur) => acc cur, 0);
console.log(sum)*/
}
All the arrays are always empty exept for the last one, it doesnt save the others. And if I write the code of the submit() into checkpercentage() it doesn't work at all.
So the problems are two: 1- All the arrays of the single step are not saved 2- I cannot use the sum function because in "acc cur" Operator ' ' cannot be applied to types 'unknown' and 'unknown'.
I'm here for any further question, thank you :)
CodePudding user response:
I guess the issue is because you are not assigning it properly. Try using the parameter directly.
submit(allocationForm: any) {
console.log(' form submit', allocationForm);
// your another code
CodePudding user response:
I got this to work:
let singularPercentage = allocationForm?.value.Department
const myArr: number[] = Object.values(singularPercentage);
const sum = myArr.reduce((acc, cur) => acc cur, 0);
console.log(sum)
it does what I want, just the "Department" should be dynamic depending on the ngModelGroup that I have in HTML, but I couldnt make it till now