This is my response. I am looping the data needed and resources and displaying it in tiles with checkbox. I have a field cost estimation in the footer which will have usd 0(minValue) - usd 0(maxValue) at the footer. What i want to do here is onclick of checkbox i want to update the minValue and maxvalue. I can have multiple selections. I can select combination of data needed and resources. So how to do this dynamically in typescript? Any help is appreciated.
{
"DataNeeded":[
{
"MinValue":0.00,
"MaxValue":0.00
},
{
"MinValue":0.00,
"MaxValue":0.00
}
],
"Resources":[
{
"MinValue":0.00,
"MaxValue":0.00
},
{
"MinValue":0.00,
"MaxValue":0.00
},
{
"MinValue":0.00,
"MaxValue":0.00
}
]
}
CodePudding user response:
When we has an array of object (e.g. elemens) and we want "checked", we can use an auxiliar array or booleans,e.g.
<div *ngFor="let element of elements;let i=index">
<input type="checkbox" [(ngModel)]="auxArray[i]">
</div>
So, it's "easy" filter the elements selected, in a function
auxArray:boolean[]=[] //<--declare the array
getSelected(){
const selected=this.elements.filter((x,index)=>this.auxArray[index])
}
Yes the "filter" method of an array admit a second argument with the index of the iteration, so the expresion before indicate that if the array in the position 1 is true -our second check-box-, pass the filter
So we can do something interesting with the elements selected, e.g. calculate the sum of one property
<div *ngFor="let element of elements;let i=index">
<!--I divided the "banana" syntax-->
<input type="checkbox"
[ngModel]="auxArray[i]"
(ngModelChange)="auxArray[i]=$event;calculateSelect()">
</div>
the sum of MinValue is {{sum}}
And in .ts
//declare a variable sum
sum:number=0;
calculateSelect(){
const selected=this.elements.filter((x,index)=>this.auxArray[index])
this.sum=selected.reduce((a,b)=>a b.MinValue,0)
}