`The form input status color remains static and does not update`

I encountered a situation in one of my projects where I need to visually indicate if a field is correct or incorrect based on the value of another field. To better illustrate this issue, I have created an example here.

The main challenge: I am struggling to change the color status of an input based on the value of ANOTHER input.

To clarify the problem, let me walk you through it using images: Step one - I entered a larger number in the Smaller Value input and blurred it, resulting in an expected error:

https://i.sstatic.net/k6SUQ.png

Step two - I entered a bigger number in the Bigger Number input and blurred it, anticipating the Smaller Value input to turn green, but it remains red:

https://i.sstatic.net/zprUl.png

My desired outcome is as follows: Whenever the smaller value exceeds a certain threshold, its input should turn red, and when it's within the criteria, the input should be colored green.

This logic functions when I manually change the Smaller Value and blur the input. However, if I enter a smaller number in the Bigger Number input, the Smaller Value input fails to transition from green to red as expected.

Here is the form and validator function I am utilizing:

   this.thisForm = new FormGroup({
      smallerValue: new FormControl('', [
        this.validateSuccessShortName.bind(this)
      ]),
      biggerNumber:new FormControl('', [
        Validators.required
      ])
    });
  }
  validateSuccessShortName(control: AbstractControl) {
      if (parseInt(control.value,10) > parseInt(this.biggerNumber, 10)) {
        return {value: control.value};
      }
      return null;
    }

In an attempt to manually trigger validation, I implemented the following function which successfully triggers validation, but unfortunately doesn't update the validation status of the Smaller Value input based on the Bigger Number input:

updateFields(){
  for (const field in this.thisForm.controls) {
  this.thisForm.controls[field].updateValueAndValidity();
}

For a more interactive demonstration of this issue, visit this STACKBLITZ.

If you require further information, feel free to reach out!

Answer №1

Innovative solution! To effectively implement the desired functionality, manually binding the built-in classes to the ion-items is necessary:

<ion-item [class.ng-invalid]="!thisForm.controls.smallerValue.valid" [class.ng-valid]="thisForm.controls.smallerValue.valid">

Kudos to brianlittmann for sharing this insightful answer in a github discussion:

https://github.com/ionic-team/ionic/issues/6040#issuecomment-315037781

For a demonstration of this technique in action, check out the working stackblitz: https://stackblitz.com/edit/ionic-ctmumh?file=pages/home/home.html

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

issue with useReducer not functioning as expected

I encountered an issue with my customized Select component. It includes a select and options while listening for onChange events. Additionally, I am using a useReducer function that initializes some variables. However, even after selecting an option, the s ...

Matter of Representing Nested For Loops in Javascript Arrays

When I have two arrays that intersect at certain elements, the resulting function should ideally output A, B, Y. However, in this case, it displays all possible combinations of lista.length * listb.length. <script> window.onload = function(){ ...

The file is missing the required fields in the Firestore document

I've been facing a challenge while attempting to update specific fields within a firebase document. Even though the cloud function triggers and performs an upload on the document, the values of the fields I am trying to update never seem to get upload ...

What is the best method for retrieving the entire row data based on the maximum value in a column?

function findMaxValue() { var highestValue = Math.max.apply(Math, $('.sira').map(function() { return $(this).text() })) alert(highestValue); } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"& ...

How can I set a header to be automatically included in every "render" response in Node.js/Express?

One of the challenges I face involves implementing "controllers" in my code: app.get('/',function(req,res){ var stuff = { 'title': 'blah' }; res.render('mytemplate',stuff); }); In particular, I'm worki ...

Deploying my app on Heroku with two separate folders: a step-by-step guide

I am currently working on a project that involves two separate folders - one for the frontend and another for the back-end. My goal is to deploy both of these folders onto a single Heroku app. Within the server.js file, I have the following code snippet: ...

Tips for handling errors when the ID parameter in the URL doesn't correspond to the ID in the database and redirecting to an error page

Utilizing a MERN stack application, I rely on the Axios library to facilitate communication between the client and server. An essential route '/blogs' is responsible for fetching all the blogs from the backend and presenting them on the interface ...

Safari having trouble auto-playing Vimeo iframe embed

Update 6/26/23: Seems like a mysterious change occurred, as now the Vimeo video on project pages is playing automatically for me in Safari without any specific reason. It's working fine on Chrome too. Not sure if Vimeo made an update or if it's r ...

Issues with response functionality in Node.js (Openshift) using express

I am currently working with OpenShift and Node.js to calculate the average rating for each result. However, I am facing an issue where the response is not being displayed even though the console logs show the correct data. The console displays 3.9454323, ...

Nuxt middleware failing to verify user's logged-in status

I am currently working on implementing user authentication and redirection logic based on the user's authentication status. For instance, if a logged-in user tries to access the login or signup page, they should be automatically redirected. To achieve ...

AngularJS text markers

In order to streamline the process of managing tags with random content, I have devised a 'tag' manipulation system using the angular-ui alert mechanism. The system includes a factory and a directive as follows: Factory: app.factory( &a ...

The light/dark mode toggle is a one-time use feature

I've been experimenting with creating a button to toggle between light and dark modes on my website. Initially, it's set to light mode, but when I try switching to dark mode, it works fine. However, the issue arises when attempting to switch back ...

Utilize Vue 3 for setting up reactive fetching with asynchronous JSON handling

I recently upgraded to Vue 3 and I'm trying to populate a reactive object by fetching data from a JSON API. Here's how my component looks. Surprisingly, I am not encountering any errors but the expected results are not showing up either. <tem ...

Angular 2: Implementing service functions on button click using the (click) event

Is it possible to call a function from my service when clicking on an element in the HTML returned from an HTTP call? Here is the HTML snippet: <a (click)="SellingVarietiesService.goToVarietyDetails(3)">Test</a> The function I want to call i ...

Using an external HTML file to import a template into Vue.js single file components

I've been tackling a Vuejs project that involves using vue-property-decorator in single file components. I'm trying to figure out how to import the template from an external HTML (or different) file, but so far I haven't found a solution. I& ...

The functionality of Ajax autocomplete with jQuery does not function properly when the text field contains existing text

Currently, I am utilizing Ajax autocomplete for jquery in my project. Below is the HTML code snippet I have implemented: <input type="text" name="autocomplete" id="globalBCCAutoComplete"> Furthermore, here is the JS code utilized for the autocomple ...

Troubleshooting npm test failure on CircleCI due to inability to locate installed package

It's puzzling that Circle is encountering issues with utilizing ts-mocha after it was successfully installed with npm install in a previous step of the build process. The functionality used to function properly, but now it suddenly stopped working. ...

Animating objects in ThreeJS to traverse multiple positions smoothly with linear interpolation (lerp)

I am exploring ways to animate a sphere's movement along a predefined sequence of vertices. I have successfully managed to animate the sphere from one point to another using the code below: function animate() { requestAnimationFrame(animate) spher ...

Storing JWT API tokens in a secure location

Currently, I am in the process of developing the API portion for an application and focusing on implementing JWT authentication. At this point, I am generating a token and sending it back to the front-end as part of a JSON object when a user is created. Ho ...

Exploring Angular2 utilizing matrix-style URL notation

Which is the preferred method for creating URLs with parameters - using matrix url notation or the traditional ? and & format? I found the explanation in the angular.io documentation confusing. localhost:3000/heroes;id=15;foo=foo or localhost:3000/h ...