Angular Material 2: возникли проблемы с отображением вновь созданного массива внутри функции

Я пытаюсь создать калькулятор штанги, где пользователь вводит желаемый общий вес и вес штанги, и приложение будет отображать, какие веса им нужны с каждой стороны. На данный момент это все еще довольно просто, но я столкнулся с проблемой, из-за которой я немного озадачен. Внутри моего компонента «фунты» я пытаюсь рассчитать вес, необходимый для каждой стороны. Часть Кодекса с комментариями:

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. Любая помощь приветствуется, спасибо.


person chernabog_94    schedule 23.06.2017    source источник
comment
возможно, стоит сделать plunker из вашего кода, чтобы вам было намного проще помочь.   -  person Ahmed Musallam    schedule 24.06.2017
comment
@chernabog_94 каков результат вашего console.log в console.log(platesUsed); ?   -  person Emile Cantero    schedule 24.06.2017


Ответы (1)


Вы инициируете idsUsed внутри функции calc() из-за того, что представление компонента не имеет на нее ссылки. Я инициализировал idsUsed вне функции calc(), и она начала работать.

Вот plnkr демонстрация вашего кода, надеюсь, это то, что вы ищете.

public barWeight: string = '45';
public totalWeight: string = '';
public weight: number = 0;

public idsUsed = []

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},
];

constructor() {

  }

// 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 = [];
    this.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) {
        this.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(this.idsUsed);
console.log(platesUsed);
console.log(totalUsed); 
return {remaining: this.weight} 
 }  
person Nehal    schedule 24.06.2017
comment
Большое спасибо за код plnkr. Я понимаю, что запуск idsUsed вне функции calc() позволяет отображать пластины в представлении, но это как бы портит расчет. Например, я ввел 3 значения для расчета программой: 135, 155, 165. Вот журнал консоли результаты, которые показывают правильные веса с соответствующими идентификаторами. Это результаты тех же значений в коде plunkr, который вы предоставили. Изображения пластин кажутся продолжать добавлять друг к другу. - person chernabog_94; 26.06.2017
comment
Извините, я не знал о путанице в расчетах, сосредоточился на том, чтобы заполнить изображения. Я поработаю над исправлением в демо и дам вам знать. - person Nehal; 26.06.2017
comment
Итак, я добавил строку для сброса idsUsed в начале calc(). Из моего тестирования показалось, что это совпадает с вашими результатами. Проверьте plnkr еще раз и дайте мне знать, если проблема не устранена, спасибо! - person Nehal; 26.06.2017
comment
Ничего себе, это сделал это. Спасибо, что уделили этому время. - person chernabog_94; 26.06.2017