Я пытаюсь создать калькулятор штанги, где пользователь вводит желаемый общий вес и вес штанги, и приложение будет отображать, какие веса им нужны с каждой стороны. На данный момент это все еще довольно просто, но я столкнулся с проблемой, из-за которой я немного озадачен. Внутри моего компонента «фунты» я пытаюсь рассчитать вес, необходимый для каждой стороны. Часть Кодекса с комментариями:
public barWeight: string = '45';
public totalWeight: string = '';
public weight: number = 0;
public plates= [
{ weights: 100, id: 2, value: false},
{ weights: 45, id: 3, value: true},
{ weights: 35, id: 4, value: true},
{ weights: 25, id: 5, value: true},
{ weights: 10, id: 6, value: true},
{ weights: 5, id: 7, value: true},
{ weights: 2.5, id: 8, value: true},
{ weights: 1.25, id: 9, value: false},
];
// Filters out the plate array by value,
// which in this case are checkboxes the user can toggle.
get selectedPlates() {
return this.plates
.filter(plate => plate.value)
}
public calc() {
this.weight = ((parseFloat(this.totalWeight) - parseFloat(this.barWeight)) / 2);
var totalUsed = [];
var idsUsed = [] ;
var exp = 1; // just used to keep track of the count
var platesUsed = [];
//Beginning of calculation of weights on each side
for (let i = 0; i < this.selectedPlates.length; i += 1) {
let count = 0
while (this.weight >= this.selectedPlates[i].weights) {
this.weight -= this.selectedPlates[i].weights
count += 1
}
if (count >= 1) {
exp = count
totalUsed.push(this.selectedPlates[i].weights)
totalUsed.push(this.selectedPlates[i].id)
}
}
//loop that gets every other element of totalUsed array starting with the first element
// AKA just displays the ID's of the weights
for (let i = 0; i < totalUsed.length; i += 2) {
idsUsed.push(totalUsed[i + 1]);
}
//loop that gets every other element of totalUsed array starting with the second element
//AKA just displays the weights without their IDs
for (let i = 0; i < totalUsed.length; i += 2) {
platesUsed.push(totalUsed[i]);
}
console.log(exp);
console.log(idsUsed);
console.log(platesUsed);
console.log(totalUsed);
return {remaining: this.weight}
}
}
Calc() — это функция щелчка, предназначенная для вычисления весов. Это, вероятно, довольно запутанно и неполно, но проблема здесь в том, что я не могу отобразить какие-либо созданные массивы, которые находятся в calc(). В данном случае это будет idsUsed. Я присвоил изображения пластин для тяжелой атлетики по значению id. Хотя на данный момент это просто общедоступный URL-адрес, я собираюсь изменить его намного позже. Я пытаюсь отобразить их в списке сетки
Вот соответствующие фрагменты изpound.component.html.
<md-card>
<md-input-container>
<input [(ngModel)]="barWeight" mdInput placeholder="Bar Weight" dividerColor="accent">
</md-input-container>
<md-input-container>
<input [(ngModel)]="totalWeight" mdInput placeholder="Total Weight" dividerColor="accent">
</md-input-container>
<button md-raised-button color="primary" (click)="calc()">CALCULATE</button>
</md-card>
<md-card>
<md-checkbox *ngFor="let plate of plates"
[(ngModel)]="plate.value">
{{plate.weights}}
</md-checkbox>
</md-card>
<md-card>
<md-card-content>
<md-grid-list cols="4" rowHeight="200px">
<md-grid-tile *ngFor="let idUsed of idsUsed">
<img src="http://www.roguefitness.com/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/r/o/rogue-calibrated-lb-steel-plates-web{{idUsed}}.jpg" layout-fill>
</md-grid-tile>
</md-grid-list>
</md-card-content>
Everything comes out blank. In the console log, I get the values I need, but I'm assuming that they are displaying because they're within calc(). If I move the variables outside of calc() the ngFor grid list will work, but the loops within calc() don't work properly, so the results are all over the place.
Я не уверен, как правильно отображать idsUsed. Любая помощь приветствуется, спасибо.