Check if a form field's value is lower than another in Angular reactive forms

In the form, I have a field called LDC along with two other fields named limit1 and limit2. My goal is to display an error message if either limit1 or limit2 exceeds the value of LDC, or if the sum of limit1 and limit2 surpasses LDC. I attempted to create a custom validator for this scenario, but it did not function as expected. I came across rxwebvalidators and I'm wondering if it's possible to customize error messages for these validators. Any assistance on this matter would be greatly appreciated. Thank you in advance.

Answer №1

To easily handle errors, you can start by initializing a boolean variable like this:

hasError = false;

Then, you can listen to value changes for each field:

limit1.valueChanges().pipe(
   distinctUntilChanged()
).subscribe(value => {
  if (value + limit2.value < LDC) { // LDC is not defined here
    this.hasError = true;
  } else {
    this.hasError = false;
  }   
});

Repeat the same process for limit2 (assuming both are FormControls).

In your template, you can show or hide the error message using the ngIf directive like this:

<div>
  <input .... >
  <span *ngIf="hasError">Error message</span>
</div>

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

A guide to implementing typescript with Next.js getStaticProps

I have Next.js set up with the TypeScript feature enabled Currently, I am attempting to utilize the getStaticProps function following the guidelines outlined here: https://nextjs.org/docs/basic-features/typescript Utilizing the GetStaticProps type export ...

A helpful guide on fetching the Response object within a NestJS GraphQL resolver

Is there a way to pass @Res() into my graphql resolvers and make it work correctly? I tried the following, but it didn't work as expected: @Mutation(() => String) login(@Args('loginInput') loginInput: LoginInput, @Res() res: Response) ...

Guide on importing CDN Vue into a vanilla Typescript file without using Vue CLI?

In the midst of a large project that is mostly developed, I find myself needing to integrate Vue.js for specific small sections of the application. To achieve this, I have opted to import Vue.js using a CDN version and a <script> </script> tag ...

Error TS2339: The specified property is not found within the given type of 'IntrinsicAttributes & IntrinsicClassAttributes<FormInstance<{}, Partial<ConfigProps<{}, {}>>>> & ...'

Recently diving into the world of TypeScript and Redux, I've been tackling the SimpleForm example from redux-form. Below is the form component I'm working with: import * as React from 'react'; import {Field, reduxForm} from 'redu ...

What is the method to incorporate the current time into a date object and obtain its ISO string representation?

I'm using a ngbDatePicker feature to select a date, which then returns an object structured like this: {year:2020, month:12, day:03} My goal is to convert this date into an ISOString format with the current time. For example, if the current time is 1 ...

Retrieve values from a multi-level nested object by using square bracket notation for each level

I am in need of a config object to display nested data. Check out the demo code for reference In the code, accessing "customer.something" is essential. There can be multiple levels of nesting, which the grid handles with field='customer.som ...

Creating a Union Type from a JavaScript Map in Typescript

I am struggling to create a union type based on the keys of a Map. Below is a simple example illustrating what I am attempting to achieve: const myMap = new Map ([ ['one', <IconOne/>], ['two', <IconTwo/>], ['three ...

Incorporating Sass into a TypeScript-enabled Create React App

Having recently transferred a create-react-app to typescript, I've encountered an issue where my scss files are not being recognized in the .tsx components. The way I'm importing them is as follows: import './styles/scss/style.scss'; ...

Why is it not possible to declare an interface or type within a TypeScript class?

I am struggling to define interface | type within a TypeScript class. Here is the code snippet: class MyClass { interface IClass { name: string, id: string } } However, I keep encountering this error: Unexpected token. A constructo ...

Is there a way to deactivate the click function in ngx-quill editor for angular when it is empty?

In the following ngx-quill editor, users can input text that will be displayed when a click button is pressed. However, there is an issue I am currently facing: I am able to click the button even if no text has been entered, and this behavior continues li ...

Converting a JavaScript function to work in TypeScript: a step-by-step guide

When writing it like this, using the this keyword is not possible. LoadDrawing(drawing_name) { this.glg.LoadWidgetFromURL(drawing_name, null, this.LoadCB,drawing_name); } LoadCB(drawing, drawing_name) { if (drawing == null) { return; ...

Exploring TypeScript: Understanding how to define Object types with variable properties names

Having an issue with a React + TypeScript challenge that isn't causing my app to crash, but I still want to resolve this lingering doubt! It's more of a query than a problem! My goal is to set the property names of an object dynamically using va ...

Anticipated the object to be a type of ScalarObservable, yet it turned out to be an

When working on my Angular project, I utilized Observables in a specific manner: getItem(id): Observable<Object> { return this.myApi.myMethod(...); // returns an Observable } Later, during unit testing, I successfully tested it like so: it(&apos ...

Exploring Computed Properties in Angular Models

We are currently in the process of developing an application that involves the following models: interface IEmployee{ firstName?: string; lastName?: string; } export class Employee implements IEmployee{ public firstName?: string; public l ...

The state is not being updated immediately when trying to set the state in this React component

Currently, I am working on a React component that is listening to the event keypress: import * as React from "react"; import { render } from "react-dom"; function App() { const [keys, setKeys] = React.useState<string[]>([]); ...

Injecting configurable middleware dependencies in Nest.js allows for dynamic customization of middleware

While many tutorials demonstrate how to inject providers into dynamic modules, most of them only focus on services and not middleware. The challenge arises when attempting to create reusable middleware that also requires injected providers. For instance, ...

Enhance Component Reusability in React by Utilizing Typescript

As I embark on developing a React application, my primary goal is to keep my code DRY. This project marks my first experience with Typescript, and I am grappling with the challenge of ensuring reusability in my components where JSX remains consistent acros ...

Typescript validation of tokens using Azure functions

Currently working on a website utilizing Azure Static Web App, where the login/registration is managed by Azure B2C. The backend API consists of typescript Azure functions integrated with Azure Static web app. Certain API calls can only be accessed when th ...

What are some strategies for exporting methods without resorting to the use of import * as ...?

Imagine having a file structured like this: // HelperFunctions.ts export const dateFormat = 'MM/DD/YYYY'; export const isEmpty = (input: string | null | undefined): boolean => { if (input == null) { return true; } if (!in ...

What are the steps to lift non-React statics using TypeScript and styled-components?

In my code, I have defined three static properties (Header, Body, and Footer) for a Dialog component. However, when I wrap the Dialog component in styled-components, TypeScript throws an error. The error message states: Property 'Header' does no ...