In a scenario where a specific element is disabled, how can I link its value to another related element?

Setting:

Ionic version: 6.20.1

Angular CLI version: 10.0.8

In the process of developing a mobile expense management application, I am working on implementing a feature that calculates the recommended spending for different categories (e.g., home expenses).

Issue:

I have checkboxes representing various spending categories (e.g., home ❏, education ❏, entertainment ❏) that users can select or deselect. These categories are interconnected in such a way that if one is deactivated, its percentage is added to another related category (e.g., deactivating "Home 15%" adds its percentage to "Shopping 6%"). This selection is saved in the database and retrieved to determine the recommended spend percentages.

Objective:

I would like to handle the following conditions when a category is disabled:

  • If a category is deactivated (false), its value shifts to its related category.

  • If two related categories are deactivated, their values are transferred to a third related category (e.g., deactivating "Home 15%", "Shopping 6%" transfers their values to "Food -> 49%").

  • If three linked categories are disabled, a portion of their values is moved to savings (worth 10% of the total) and the rest to another category.

Proposed Solution:

To address this issue, I have designed a set of conditions covering all categories so that if one is false, its value passes to the appropriate related category. Here is an example code snippet demonstrating this approach:

// Example implementation to handle shifting values based on category deactivation

// Check if 'Home' is deactivated and redistribute value accordingly
if (i.home == false && i.shopping == true && ... && i.entertainment == true) {
    this.sumaCatPurchases = (this.sumaTotalIncomes * 0.21).toFixed(2);
    // Assign similar calculations for other categories as needed
}

This method helps maintain the integrity of each category's default value while ensuring seamless value transfer upon deactivation of a specific category.

However, the drawback of this approach is the extensive manual coding required for handling multiple scenarios involving category deselection. If numerous categories need to be managed simultaneously, the complexity grows exponentially, making it impractical to cover all possible combinations individually.

If anyone has insights or suggestions on how to improve this process and make it more efficient, I would greatly appreciate your input.

Answer №1

It seems that you have a scenario where there is a list of items with corresponding percentages. When an item is unchecked, its percentage should be added to the next checked item and values should be redistributed based on the new percentages.

One approach to tackle this is by utilizing events. If you are using ion-checkbox, you can monitor checkbox changes through the ionChange event. Essentially, when a checkbox is unchecked, you can identify the next related checked item and transfer the percentage value from the unchecked item to the checked one. Subsequently, adjust the values according to the updated percentages. Then, when a checkbox is checked, recursively search for preceding unchecked items and aggregate their values to the current one.

Below is an illustration demonstrating how you can achieve this:

HTML snippet for the first item:

<ion-checkbox (ionChange)="checkBoxChanged(1, $event)"></ion-checkbox>
<ion-label>home: {{itemsCurrentValues[1]}}</ion-label>

TypeScript code:

checkBoxChanged(id: number, event: CustomEvent){
    isChecked[id] = event.detail.checked;
    if(event.detail.checked === false){
        // Increase the percentage value of the next related checked item, for instance:
        if(nextAvailableRelated(id) >= 0){
            itemsPercentageValues[nextAvailableRelated(id)] += itemsPercentageValues[id];
            // Update the current value of the next one:
            itemsCurrentValues[nextAvailableRelated(id)] = itemsPercentageValues[nextAvailableRelated(id)]*sumaTotalIncome;
        }
        // Reset the percentage value of this item:
        itemsPercentageValues[id] = 0;
        // Then update the current values accordingly:
        itemsCurrentValues[id] = itemsPercentageValues[id]*sumaTotalIncome;
    }
    else{
        // Decrease the percentage value of the next related checked item, for example:
        if(nextAvailableRelated(id) >= 0){
            itemsPercentageValues[nextAvailableRelated(id)] -= itemsBaseValues[id]
            // Update the current value of the next one:
            itemsCurrentValues[nextAvailableRelated(id)] = itemsPercentageValues[nextAvailableRelated(id)]*sumaTotalIncome;
        }
        // Restore the original percentage value of this item:
        itemsPercentageValues[id] = itemsBaseValues[id] + previousUncheckedValuesSum(id);
        // Update the current values accordingly:
        itemsCurrentValues[id] = itemsPercentageValues[id]*sumaTotalIncome;
    }
}
// This function calculates the cumulative sum of percentage values of unchecked items prior to the current item in the relation chain
previousUncheckedValuesSum(id){
    if(previousItem(id) < 0 ||  isChecked[previousItem(id)] === true){
        return 0;
    }
    else{
        return previousUncheckedValuesSum(previousItem(id)) + itemsBaseValues(previousItem(id));
    }
}

In this context, itemsPercentageValues stores the current item percentages, itemsBaseValues represents the initial percentage values, itemsCurrentValues tracks the final values of each item, nextAvailableRelated(id) determines the next checked item in the related chain, and previousItem(id) finds the associated item of the current item. It might seem intricate, but I trust my demonstration clarifies the process.

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

Different method for uploading json documents to Firebase's live database

Recently, while following a Google codelabs tutorial on creating a chat app, I encountered an issue with importing a JSON file into the realtime database. The tutorial can be found at . The instructions were to access the Database section in the Firebase ...

Encountering Type Error in Angular 2

Here is the Angular 2 code snippet I am working with: <ion-grid *ngFor="let item of menuData; let i = index;" ng-init="getAllItemToGrid()"> <img src="{{'assets/Products/'+menuData[i].image}}" ng-click="onLogin()" width="100%"> ...

Experiencing complications with an Angular 2 router

When a user logs into the system, they are greeted with a navigation bar featuring options like Dashboard, Customers, and Product. Below is an excerpt from my routes file: app.routing.ts export const router: Routes = [ { path: '', redir ...

Modify the field key within the Cloud Firestore

Is it possible to update the key itself instead of its value in Firestore? For example, changing from key: value to key2: value. Thanks ...

Tips for implementing simple custom styling within an Angular application without relying on innerHTML

Seeking advice on the best practices for a specific scenario. I am currently developing a small Angular application where users can input text. I would like to allow them to easily make certain words bold or create links. For example, if they type *whatev ...

Ways to bypass browser pop-up blockers when using the window.open function

I am displaying an HTML retrieved from the backend. printHtml(htmlContent) { var windowToPrint = window.open('', '_blank'); windowToPrint.document.write(htmlContent); setTimeout(function () { windowToPrint.document ...

Issue: When using Android Kotlin to add an item to an Array<JSONObject> or JSONArray, it is causing an Array

Currently, I am encountering an issue where I need to convert a mutable list into a JSON array in order to send it to the next activity. It seems impossible to directly pass the mutable list without including any serialization plugin. This is the code sni ...

Angular and PrimeNG's P-dialog positioning feature seem to be having trouble coordinating effectively,

I've been attempting this with no success, utilizing Angular 8 and Primeng version 9.0.0-rc.4. Thank you for your help. <p-dialog position="right" header="Change Password" (visible)]="display"> Content </p-dialog> Check out more her ...

Issue with Angular 2 NgFor Pattern Error Message Display Absence

I am attempting to incorporate inputs with a regex requirement within an ngFor loop, but I am not receiving the expected error message when entering something that does not match the required pattern. Even when I input an incorrect pattern, "Test" remains ...

Can you identify the TypeScript type for an array containing various Angular components?

In my application, I have a diverse range of components that I would like to organize into an array. There are no restrictions on what types of components can be included in this array, as long as they are Angular components. What is the correct way to de ...

Prohibit the use of explicit type parameters or limit the union type parameters to enhance the safety of the types

When the getValues() function is called without explicit type parameters, the Typescript code functions correctly. However, calling it with explicit type parameters can result in errors (as seen in invocation getValues<'a' | 'b' | &a ...

Connecting an Android ListView with Socket.io using JSONObject

I developed a communication app using socket.io and node.js, which retrieves data in the form of a JSON object. This is my code snippet: db.query('select email from users ', function(err, rows , field) { if (err) throw err; let ge ...

When properties remain unchanged, they do not hold the same value in a Firestore-triggered Cloud Function

Within my Firestore database, there is a collection named events consisting of documents with attributes such as begin, end, and title. The function in question is triggered when any changes occur within a document. The begin and end fields are both categ ...

Logging errors in Firebase Analytics using Swift 3

I encountered the following error while using Xcode. Even after adjusting the scheme as per some suggestions related to Firebase errors, I have not been able to resolve it. This issue is concerning as it may affect the app's acceptance on the App Stor ...

Exploring the concept of type inheritance in TypeScript

I am working on developing various components for an app, each with its own specific structure. The general structure is defined as COMPONENT. Within this framework, there are two distinct components: HEADING and TEXT. These components should be subclasses ...

Displaying the initial element in an NgFor loop in Angular 2

Whenever I click on the "Add row" button, I dynamically generate a row of inputs and dropdowns. Upon clicking another button, the complete data is submitted and displayed in console.log as an array of objects, with each object representing a single row. C ...

Transforming date and timezone offset into an isoDate format using moment.js

When retrieving data from the API, I encounter Date, Time, and Offset values in separate columns. My goal is to obtain an ISO date while maintaining the original date and time values. const date = "2019-04-15" const time = "13:45" const ...

Issue encountered: The function this.http.post in Ionic 3 is not recognized as a valid function

As someone who is new to Ionic 3 & Angular 4, I am currently working on creating a login page that sends email and password data to an API. However, I keep encountering the error message "this.http.post is not a function". Despite my efforts to find a solu ...

What is the best way to utilize typed variables as types with identical names in Typescript?

Utilizing THREE.js with Typescript allows you to use identical names for types and code. For instance: import * as THREE from '/build/three.module.js' // The following line employs THREE.Scene as type and code const scene: THREE.Scene = new THRE ...

Having trouble resolving all parameters for AuthService in Angular

Launching my angular app has hit a roadblock with this perplexing error. Despite attempts to troubleshoot by removing the auth service provider and constructor reference from my component, the issue persists. As a novice in angular, I'm struggling to ...