Struggling to showcase a recently created array in a function while using Angular Material 2

I'm currently working on developing a Barbell plate calculator that allows users to input the desired total weight and barbell weight, after which the application will show them the weights needed on each side. Although it's in its early stages, I've hit a roadblock where I'm seeking some guidance. The challenge lies within my "pounds" component where I aim to calculate the required weight distribution. Here are some snippets of the code with explanations:

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

// Filtering out selected plates based on user checkboxes
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; // used for counting
    var platesUsed = [];
    
    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);
        }
    }

    for (let i = 0; i < totalUsed.length; i += 2) {
        idsUsed.push(totalUsed[i + 1]);
    }

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

The Calc() function is meant to calculate the weights when clicked. Displaying arrays created within calc(), like idsUsed, is problematic. Currently, I have associated pictures of weightlifting plates with ID values using public URLs, but this will be changed later. My goal is to showcase them in a grid list.

Here are relevant excerpts from pounds.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>

Despite obtaining the necessary values in console logs, I can't seem to get idsUsed to display properly. Any assistance would be greatly appreciated. Thank you for your help.

Answer №1

By moving the initialization of idsUsed outside of the calc() function, the component view now has a reference to it. This simple change resolved the issue and the functionality started working as intended.

If you're interested, check out the plnkr demo showcasing your code solution.

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() {

}

// The selectedPlates property filters out plate array items based on user-selected checkboxes.
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; // Used for counting purposes
    
    // 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) 
        }
    }
    
    for (let i = 0; i < totalUsed.length; i += 2) {
        this.idsUsed.push(totalUsed[i + 1]);
    }

    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} 
 }  

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Reading from [] is not permitted

I have a script where I am attempting the following action $data[] = self::get($row['sr_id']); // <-- line 55 Unfortunately, PHP is throwing an error and not allowing me to execute this code Fatal error: Cannot use [] for reading in /file ...

What could be causing the NodeJs cluster module to be malfunctioning?

Currently, I am in the process of constructing an express server and have been exploring the concept of scaling NodeJS applications. Upon my research, one of the initial things that caught my eye was the built-in cluster module which allows for leveraging ...

Encountered a hitch while trying to start an angular 2 app using npm

Encountering an error while compiling the application with @angular/cli version 1.2.4 @angular/cli: 1.2.4 node: 8.11.1 os: win32 x64 @angular/animations: 4.3.6 @angular/common: 4.3.6 @angular/compiler: 4.3.6 @an ...

Display a dropdown menu in Angular when the "@" symbol is typed into an input field

I am trying to achieve the functionality where a dropdown menu is displayed when @ is typed in the input field. The Custom Component myControl: FormControl = new FormControl(); options = [ 'One', 'Two', 'Three&ap ...

Locate the position of an item in an array based on a certain value assigned to a particular

I am trying to locate the index number of a specific item within my object. Here is the object in question: [ { "type": "Grayscale", "mode": "average" }, { "type": "Sepia" }, { "type": "Invert", "invert": true }, { "type": ...

Typescript fails to recognize a value assigned within an await statement

Looking at the code snippet below, we see that the variable x starts off undefined and can later be assigned a value of 1 within an `await` promise. Despite setting x to 1 inside the awaited promise, TypeScript still perceives it as undefined after the pr ...

Inquiries regarding Swift programming and JSON data interchange

Just starting out in Swift and exploring Stickers at the moment. I've got a JSON file with this layout: { "stickers": [{ "filename": "happy_face", "description": "Happy Face", "premium": "false", "categories": ["blue", "green", "red ...

Passing a one-dimensional array into std::thread is not possible

This example is derived from my current project, but I have created a simpler version for demonstration purposes (inspired by Lightness Races in Orbit). #include <thread> #include <iostream> class Foo { Foo(int n = 10) { size_ ...

Tips for using a fluent interface to apply a method to all data member variables simultaneously

I have a class structured as follows: class example{ private $foo = array(); private $bar = array(); public function getFoo(){ return $this->foo; } public function getBar(){ return $this->bar; } //fo ...

The Vuetify data-table header array is having trouble accepting empty child associations

My Vuetify data-table relies on a localAuthority prop from a rails backend. Everything runs smoothly until an empty child association (nested attribute) is passed, specifically 'county': <script> import axios from "axios"; exp ...

Struggling to retrieve all the properties of an Entity in TypeORM and NestJS

I've been working on building a server using typeORM and NestJS. I have set up a one-to-one relationship between my User and Shop classes, with the foreign key shopId in the User table. However, when trying to retrieve a user, the associated shop is n ...

I'm trying to reverse the order of my array, but for some reason the collections aren't working correctly

Below is the code snippet that I am having trouble with: public void p10(int a, int b, int c){ int[] nums = new int[] {a, b, c}; Arrays.sort(nums, Collections.reverseOrder()); System.out.println(Arrays.toString(nums)); } I am encountering an e ...

After reloading the component, I encountered difficulties subscribing again to the BehaviorSubject for a second time

After reading recommendations to always unsubscribe when removing a component, I encountered an issue in my code. The error object unsubscribed occurs when navigating between child components and trying to resubscribe to a BehaviorSubject. Even though I am ...

What could be causing axios to not function properly when used with async/await in this particular scenario

I need to update the DoorState when a button is clicked. After sending a request to the API to change the DoorState, I then call another API to check the status of the robot. Even though the DoorState has been successfully changed, it seems that the chan ...

Issues with Karma Testing: None of the Tests Executed Successfully

I am currently enrolled in the Angular Fundamentals course presented by Jim Cooper on Pluralsight. Despite following the course meticulously, using the same versions, and replicating the code exactly, I am facing an issue with running my Karma tests. Belo ...

Building an Elegant Tab Menu with Ionic 2 Components

Just diving into the world of Ionic 2 and Angular 2. I'm attempting to include a tab menu component in some of my pages, but struggling. Here's the code for the menu.component.ts file: import { Component, OnInit } from '@angular/core' ...

Utilizing Node.JS and Typescript to correctly define database configuration using module.exports

I am currently utilizing Mongoose in my node.js application, which is written in Typescript. The Mongoose documentation provides clear instructions on how to connect to their database like this, but I prefer to have the configuration stored in a separate ...

What steps should I take to resolve an Angular error that occurred following the installation of Font Awesome

After installing font awesome, I encountered this error: Uncaught TypeError: Class constructor Platform cannot be invoked without 'new' at Module../node_modules/@angular/cdk/ivy_ngcc/fesm2015/platform.js (platform.js:78) at webpack_require (boo ...

What is the purpose of the tabindex in the MUI Modal component?

Struggling with integrating a modal into my project - it's refusing to close and taking up the entire screen height. On inspection, I found this troublesome code: [tabindex]: outline: none; height: 100% How can I remove height: 100% from the ...

Can you explain the significance of this particular method signature in the TypeScript code snippet shown above?

Referencing the ngrx example, we encounter the code snippet for the method store.select, which has a complex signature with two arrows. What is the significance of this method signature? The interface definition in the type file presents the following sig ...