Tips for resolving logical errors in Angular's if statements

I have a straightforward logic with conditions written, but I am always getting inaccurate results. I am dealing with three fields: immediate limit, hold limit, and LDC. The condition I am trying to implement is that when the immediate limit and hold limit are numeric values, their sum should be less than LDC, and each individual limit should also be less than LDC. If the limit values are not numeric, they return a negative number.

Below is my code:

immediateLimitError: boolean = false;
hold1LimitError: boolean = false;
ldcLimitError: boolean = false;
sumOflimitVal: any;
changedLdc!: any;
changedImmediateLimit!: any;
changedHold1Limit!: any;

private instantiateValidation(row: any) {
        this.newHoldSchedule = this.formBuilder.group({
            immediatereleaseForm: [(row.hold1ReleaseAmt != null ? row.hold1ReleaseAmt : ' '), Validators.required],
            ldcForm: [(row.ldcAmt != null ? row.ldcAmt : ' ')],
            holdOneLimitForm: [(row.hold2ReleaseAmt != null ? row.hold2ReleaseAmt : ' '), Validators.required]
        });
        this.changedImmediateLimit = row.hold1ReleaseAmt;
        this.changedHold1Limit = row.hold2ReleaseAmt;
        this.changedLdc = row.ldcAmt;

        this.newHoldSchedule.get('immediatereleaseForm')!.valueChanges.subscribe(val => {
            this.changedImmediateLimit = val;
            if(this.changedHold1Limit >= 0 || val >= 0 ){
                if((val + this.changedHold1Limit) > this.changedLdc || 
                    val > this.changedLdc || 
                    this.changedHold1Limit > this.changedLdc){
                        this.immediateLimitError = true;
                }
                else{
                    this.immediateLimitError = false;

                }
            }
          });

          // More code...

}

if(this.immediateLimitError || this.hold1LimitError || this.ldcLimitError){
                    this.displayError('The sum of Immediate Release limit and Hold 1 Limit exceeds LDC');
                    event.preventDefault();
                }

This code works correctly for some values but produces inaccurate results for others. I have tried debugging and adjusting the conditions without success. Any assistance would be greatly appreciated. Thank you.

Answer №1

It appears that all the values are being assigned asynchronously and independently. This means there is no guarantee that other values will be updated correctly before the condition check.

An alternative approach would be to utilize RxJS combineLatest function to merge the observables and the startWith operator to set a initial value.

You can try the following:

private instantiateValidation(row: any) {
  this.newHoldSchedule = this.formBuilder.group({
    immediatereleaseForm: [(row.hold1ReleaseAmt != null ? row.hold1ReleaseAmt : ' '), Validators.required],
    ldcForm: [(row.ldcAmt != null ? row.ldcAmt : ' ')],
    holdOneLimitForm: [(row.hold2ReleaseAmt != null ? row.hold2ReleaseAmt : ' '), Validators.required]
  });

  combineLatest(
    this.newHoldSchedule.get('immediatereleaseForm')!.valueChanges.pipe(startWith(row.hold1ReleaseAmt)),
    this.newHoldSchedule.get('holdOneLimitForm')!.valueChanges.pipe(startWith(row.hold2ReleaseAmt)),
    this.newHoldSchedule.get('ldcForm')!.valueChanges.pipe(startWith(row.ldcAmt))
  ).subscribe(
    ([changedImmediateLimit, changedHold1Limit, changedLdc]) => {
      if (
        (typeof changedImmediateLimit === "number" && typeof changedHold1Limit === "number") &&
        ((changedImmediateLimit + changedHold1Limit) < changedLdc) && 
        (changedImmediateLimit < changedLdc && changedHold1Limit < changedLdc)
      ) {
        // condition met
      } else {
        // condition not met
        this.displayError('The sum of Immediate Release limit and Hold 1 Limit exceeds LDC');
        event.preventDefault();
      }
    }
  );
}

The condition has been formulated based on your query. Feel free to customize it according to your specific needs.

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

Guidelines for redirecting to a complete URL

I am currently developing a web application using Angular 7. One of the features I need to implement is redirecting to a full URL that is retrieved from a database. The challenge here is to perform the redirect within the app without causing a full page re ...

Exploring Angular 4.3 Interceptors: A Practical Guide

I am currently working on a new app that needs authorization headers. Normally, I follow a similar approach to what is described in this article on scotch.io. However, I have recently learned that Angular 4 now fully supports HTTP Interceptors through the ...

Update the data by appending a textstringValue

Is there a way to update a field value using a string in TypeScript? The following code isn't functioning as expected: fieldName = "myForm.controls.graphicUrl"; this[fieldName].patchValue("hello"); ...

The Angular program is receiving significant data from the backend, causing the numbers to be presented in a disorganized manner within an

My Angular 7 application includes a service that fetches data from a WebApi utilizing EntityFramework to retrieve information. The issue arises when numeric fields with more than 18 digits are incorrectly displayed (e.g., the number 23434343434345353453,3 ...

Next.js is faced with a frustrating issue where images and videos are failing to display

I've been working on my Next.js 13 project with TypeScript, eslint, and Chakra UI, but I'm facing an issue with images and videos not displaying. Despite trying both the HTML <img> tag and importing Image from Chakra, the problem still per ...

Issues with card flip functionality in Firefox

I designed this animation specifically for my website to create a unique effect. The animation involves translating on the Z-axis, making it appear as though the object is getting smaller, flipping to reveal the back of the card, and then translating back. ...

Issue: Unable to locate module: Error: The system is unable to find the src/app/app.component.css file?ngResource Angular

I am encountering three issues that I cannot seem to pinpoint the mistakes. Error: Module not found: Error: Unable to locate 'C:/Users/DexSh/desktop/C# Angular/Testing/src/app/app.component.css?ngResource' in 'C:\Users\DexSh\ ...

Is there a solution for the error "Unable to persist the session" in a Next.js application that utilizes Supabase, Zustand, and Clerk.dev for authentication?

I have successfully set up a Next.js application with Clerk.dev for authentication and Supabase for data storage. I'm also leveraging Zustand for state management. However, an error is plaguing me, stating that there's "No storage option exists t ...

The message I received from my Angular 7 application is indicating that 'The specified selector does not correspond to any elements in the document.'

Using Angular 7 and I've implemented a custom component located at src/app/organization/organization.component.ts import { Component, OnInit } from '@angular/core'; import {FormGroup, FormBuilder, Validators} from "@angular/forms"; @Compo ...

Error message: "The property 'ɵunwrapWritableSignal' is not found on the type 'typeof import_modules/@angular/core/core'". Here is how you can troubleshoot this issue in HTML files

Can anyone help me resolve this error that keeps appearing in all my Angular HTML pages? I am using Node version 14.17.4 and Angular version 15. The error message states: Property 'ɵunwrapWritableSignal' does not exist on type 'typeof impor ...

conditionally trigger one observable in rxjs before the other

I am in need of assistance or guidance regarding a challenge I am facing with rxjs that I cannot seem to resolve. In essence, my goal is to trigger an observable and complete it before the original one is triggered. Scenario: I am currently working on a ...

Angular form group not providing data upon submission

Encountering a peculiar issue here. When the submit button is clicked, my angular form group does not return anything. Additionally, nothing is being logged to the console upon clicking. Interestingly, this form is almost identical to another one that func ...

Determining the Best Option: React JS vs Angular UI Framework

After researching the latest versions of React and Angular online, I discovered that both are suitable for developing Web Application UI. However, I also realized that there are key differences to consider when choosing between the two. Let's say I h ...

Is Typescript syntax for a collection of strings comparable to using string[]?

When working with Typescript, the convention to define an Array of Strings is either string[] or Array<string>. In our team, we lean towards using the more concise string[]. However, when it comes to defining a Set of Strings, is there a shorter syn ...

Switch the paper tab to a dropdown menu in Polymer.js

Can someone assist me in transforming the paper tab into a paper drop down menu in polymer JS? I want the drop-down to appear with a list of values when hovering over the Top menu. Activity Execution <paper-tab cla ...

typescript exploring the versatility of dynamic types and generics

Understanding TypeScript dynamic and generic types can be challenging for me. The goal is to create a function that generates an object with a specific type, where some properties of the object must match the parameters provided to the function. Essentia ...

Using a tuple as a key in a Map in Typescript/Javascript can be a powerful

Encountered a strange bug in my code where I'm struggling to achieve constant time lookup from a Map when using a tuple as the key. Here is an example highlighting the issue, along with the workaround I am currently using to make it function: hello. ...

Encountered an error while loading resource: net::ERR_CONNECTION_REFUSED in Nodejs

I am currently working on a form in my angular 6 app with nodejs, utilizing nodemailer for sending emails. Unfortunately, I am encountering an error that reads: Failed to load resource: net::ERR_CONNECTION_REFUSED : :3000/contact/send:1 Below is the form ...

Tips for connecting data to an HTML page with Angular 2

My code is throwing an error message while I'm debugging: Error: Uncaught (in promise): TypeError: Unable to get property 'standard' of undefined or null reference Here is the relevant part of my code: student.component.ts: this._studentSe ...

Leveraging a service/provider in an Angular 2 ES6 component

I've been struggling to get a service to work properly in my component despite trying multiple iterations and exhausting all resources on Google. I've followed examples closely, and even tried using Ionic's generator to create the provider, ...