Why is the ionChange/ngModelChange function being triggered from an ion-checkbox even though I did not specifically call it?

I have an issue with my code involving the ion-datetime and ion-check-box. I want it so that when a date is selected, the checkbox should automatically be set to false. Similarly, if the checkbox is clicked, the ion-datetime value should be cleared.

Link to Screenshot

 <form [formGroup]="registrationForm">   
    <ion-item>       
      <ion-label floating>Fecha Fin</ion-label>
      <ion-datetime displayFormat="DD-MM-YYYY" formControlName="date_end" 
                    (ngModelChange)="checkCheckEndDate()">
      </ion-datetime>
    </ion-item>
 </form>
 <ion-item>
     <ion-label>Trabajo aquí actualmente</ion-label>
     <ion-checkbox (click)="addValue()" [(ngModel)]="checked"></ion-checkbox>
 </ion-item>

The component variable for the checkbox is defined as checked: boolean = false;

Constructor:

this.registrationForm = formBuilder.group({
     date_end: ['',]
 });

Special Functions:

addValue(): void {
    alert("addValue"+this.checked);
    if(this.checked){
      this.registrationForm.controls['date_end'].setValue('');
    }
  }

  checkCheckEndDate(){
    alert("checkCheckEndDate");
    if(this.registrationForm.controls['date_end'])
    {
      alert("if"+this.registrationForm.controls['date_end'].value)
      this.checked=false;
      alert(this.checked);
    }else{
      alert("no"+this.registrationForm.controls['date_end'].value)
      this.checked=true;
      alert(this.checked);
    }
  }

My question is, why does checkCheckEndDate() execute when I click on the checkbox?

Answer №1

Whenever the value of the ion-datetime element changes, the checkCheckEndDate method is triggered, and this change is initiated within the addValue method which responds to a click on the ion-checkbox. This behavior is intentional and expected.

Please be aware that Angular core developers caution against mixing reactive forms with ngModel. The desired functionality can still be achieved without using ngModel by configuring an Observable on both fields and observing for changes using valueChanges.

To monitor changes in the date_end field and update the status of the ion-checkbox, you can implement code similar to the following after initializing the FormGroup:

this.registrationForm.get('date_end').valueChanges.subscribe(val => this.checked = !val);

By implementing this code, the checkCheckEndDate method becomes unnecessary.

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

"Utilize Vue i18n to properly display currency amounts in USD

Whenever I present my currency as USD, it always shows up like this: USD$500.00. I am attempting to eliminate the USD prefix from the beginning. Below is my numberFormats configuration: numberFormats: { 'en': { currency: { ...

Show dynamic outcomes on the site

I'm currently in the process of building a website for a travel search engine and I'm interested in displaying the results in a similar manner to what is done on Hipmunk. Here are some key details: The website is being developed using Django. ...

Utilizing various directives with distinct scopes for a single element

Is it possible for an element to have multiple directives with their own unique scopes? For example, let's consider a custom directive's child element with the controller's scope along with another directive (such as "ng-class"): <custo ...

Using AJAX in Classic ASP to submit a form via a POST request

My code in TEST.ASP looks like this: <HTML> <HEAD> <SCRIPT src="ajaxScript.js" type="text/javascript"></SCRIPT> </HEAD> <BODY> <FORM action="action_page.asp" method="post"> First Name:<BR> ...

How to transfer the returned value from an anonymous callback function to the `this` keyword in an ionic2 angular4 project

Currently, I am utilizing a custom geolocation provider that operates asynchronously. It takes approximately 3-5 seconds to retrieve the user's location. Using an anonymous callback function works fine when I console.log the results and view the value ...

React - The previous condition is maintained when selected

A few days back, I encountered a perplexing issue and sought help by posting a question regarding obtaining an index of values. To my relief, I received a reliable answer that enabled me to successfully tweak my existing code. One problem that arose was w ...

Error encountered while using XLSX.write in angular.js: n.t.match function is not recognized

I've encountered an issue while trying to generate an .xlsx file using the XLSX library. The error message I received is as follows: TypeError: n.t.match is not a function at Ps (xlsx.full.min.js:14) at Jd (xlsx.full.min.js:18) at Sv (xlsx.full.min ...

The JSON GET method displays HTML content when accessed through code or console, but presents a JSON object when accessed through a web address

I am currently trying to execute the following code: $(document).ready(function () { $.ajax({ url: 'http://foodfetch.us/OrderApi/locations', type: 'GET', success: function(data){ alert(data); ...

Analyzing the object for interface compatibility

When I receive a query string in one of my REST endpoints using koa-router, each value of the query string object parameter is always a string: { count: "120", result: "true", text: "ok" } Within my codebase, I have an Interface that represents the ...

Modifying the image source using state management in ReactJS

I am currently working on creating an Image slider similar to an e-commerce product in Reactjs. In regular javascript, changing the image source is straightforward, but how do we accomplish this in React? Since React involves dealing with state, it adds a ...

Alert: The lack of boundary in the multipart/form-data POST data has been detected in an unknown source on line

I am currently developing a file uploader that uploads an image when the input changes. Here is the code for my HTML form: <form method="post" enctype="multipart/form-data"> <input name="uploaded[]" type="file" id="file_upload"/> </for ...

Downloading and uploading images using AngularJS: A complete guide

I have developed an Angularjs 1.5.0 web application that needs to interact with a REST-based web service I created using dropwizard and jersey. The web service has been tested and is working perfectly. The method in the REST web service looks like this: ...

Leveraging the power of Chart.js and Ng2-Chart within the Cumulocity platform

I'm currently in the process of developing an Angular application for the Cumulocity IoT platform and I wanted to incorporate custom bar charts using Chart.js. Initially, I faced some challenges with this setup but after some research, I came across n ...

Discovering HTML attributes using part of the attribute's name

Can someone help me identify and remove all attributes in my HTML page that contain the word "data"? I want to clear out the values for these attributes. Any suggestions on how to achieve this? For instance, consider the following snippet from my HTML: & ...

What steps should I take to generate a 2-Dimension Input Array from scratch?

I am working on a project that involves creating a 2-Dimensional array of text-based numerical inputs. I aim to use the standard HTML input type box for this purpose: <input type="text"> The number of rows and columns in the array will depend o ...

Angular Form: displaying multiple hashtags within an input field

Utilizing Angular CLI and Angular Material, I have created a form to input new hashtags. I am facing difficulty in displaying previously added hashtags in the input field. Below is the code I have written: form.component.html <form [formGroup]="crea ...

Error message "Potential Undefined Object" detected on a variable that is not an object in React with TypeScript

After finding and addressing the other 5-6 questions, I managed to partially fix it by using the "!" operator. Please do not remove this question for duplication purposes. However, what baffles me is that the variable is not recognized as an object. Here i ...

Is it a problem with Cucumber Js callbacks or a feature issue?

I would like to create a scenario similar to this: Scenario: initialize new Singleton When an unmatched identity is received for the first time Then create a new tin record And establish a new bronze record And generate a new gold record This s ...

Exploring depths with Typescript recursion

I'm attempting to implement a recursive search in Typescript, but I am encountering an issue where TS is unable to determine the return type of the function. function findDirectory( directoryId: Key, directory: Directory, ) { if (!directory) ret ...

Exploring the potentials of VivagraphJS alongside WebGL and the magic of event listeners

After coming across Vivagraph JS on GitHub, I was absolutely enthralled. However, I've encountered an issue that seems to be related to WebGL. My current objective is to: var graph = Viva.Graph.graph(); var layout = Viva.Graph.Layout.forceDirec ...