The ngModel directive is causing properties to be retrieved twice

I built a simple component for displaying a list of items. Inside the component, I have an ngfor loop that includes checkboxes with [(ngModel)] bindings. Everything seems to be functioning correctly.

<div *ngFor="let armor of armorList">    
    <input type="checkbox" [(ngModel)]="armor.obtained"  />
    <span>{{armor.name}}</span>
</div>

In my code, I have implemented a get property called name (implementation removed for this example).

 get name(): string {
        console.log("test");
        return "test";
    }

One thing that has caught my attention is that when I click on the checkbox of one item in the list, the get property gets called twice for all items in the list. This behavior seems odd as I would expect it not to be called at all since I am only updating a single property of a single item.

To see this behavior in action, you can check out the example I created here. When you click on a checkbox, you'll notice that "test" is logged to the console 6 times.

If anyone has any insights or ideas on why this might be happening, please feel free to share them!

Thanks,

Leo

Answer №1

Angular reevaluates the model after updating the views to prevent any potential changes that could lead to instability. This precautionary measure ensures that updating the view does not inadvertently trigger a change in the model, thus preventing an infinite loop from occurring. If Angular detects any modifications to the model post-update, it will raise an

ExpressionChangedAfterItHasBeenCheckedError
error.

It's important to note that this behavior is specific to development mode.

If you want to delve deeper into this topic, check out this insightful article.

Answer №2

During the development mode, this function is invoked twice to ensure that the model remains unchanged. Any alteration in the model during the second call would result in an error, allowing you to identify incorrect scenarios early on. However, when building bundles in production mode, the function is only called once.

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

Displaying interactive charts in a pop-up window using Highcharts within a Bootstrap

I am looking to display a highchart inside a popover. Check out my code in this jsfiddle http://jsfiddle.net/hfiddle/abpvnys5/47/. Here is the HTML: <ul class="stat_list" style="float: left;"> <a data-toggle="popover" data-trigger="hover ...

Utilizing jQuery ajax to dynamically update map markers on Google Maps at intervals

I am currently working on a project that involves updating a Google map with a marker at regular intervals. I have an Ajax request that retrieves a single latitude and longitude coordinate, but I'm struggling to display it on the map. One option coul ...

The extended interface appears to be lacking the implementation of parent members

I am facing an issue with two interfaces export interface IComponent{ type: ComponentType; name: string; isEnabled:boolean; } export interface IAudioComponent extends IComponent { source: string; volume: number; loop: boolean; ...

Measuring the pixel distance of scrolling on a page with overflow hidden

I am trying to implement a functionality where a class is toggled for the body element on a page with hidden overflow and single screen, based on the amount of scroll. However, there is a challenge: the scrolling behavior involves animation rather than act ...

How can I connect one input field to another in Angular 2, but only if the first field is in its original pristine state

There are two input fields available: <input type="text" [(ngModel)]="title" name="title"> <input type="text" [(ngModel)]="og_title" name="og_title" value="{{ title }}"> I aim to have the og_title field match the title field until og_title is ...

I want to create a feature on my website where users can generate a random password by clicking a button on the password field. This will

After setting up a form in HTML that connects to a function in views.py within the Django framework, I decided to enhance it by adding a button that automatically populates the password field with a randomly generated password. To achieve this, I utilized ...

Anticipating the response from the API call and storing it within a variable

When I call the getLogin method within the onSubmit method, I am expecting a code to be returned that I need. However, instead of receiving the expected code, I am getting 0 as output. Can someone help me figure out what I am doing wrong? <template> ...

Splitting a loading button within post.map() in React for like/dislike functionality

I'm currently working on implementing a like/dislike feature in React. The issue I've run into is that when I try to like or dislike a post, the like/dislike buttons on all other posts are stuck in a loading state. This means that while I'm ...

Creating an event listener with a dynamic name

I'm in the process of developing a customizable button bar where I need to attach onclick event listeners to each button dynamically. The functions to be assigned should have names provided by the button's data-function attribute. … <div cl ...

Set a variable's value prior to executing an ajax request

The ajax call seems to be using the default value of the variable rather than the updated value. This is possibly due to the asynchronous nature of the call. jQuery $(".add-spouse").on("click", function(){ var spouse_ids = []; var last_id = 0; ...

Error: Unable to execute $(...).stellar since it is not a recognized function

Having some trouble implementing the stellar plugin. I've included all the necessary js, but keep getting an error in the dev tools console: 'Uncaught TypeError: $(...).stellar is not a function'. Here's what I have in the head tags: ...

Troubleshoot and resolve the issue of a page scroll freeze bug occurring while scrolling through an overflowed

My webpage features a Hero section with 2 columns - the left column contains a gallery slider, and the right column consists of 2 text blocks. The challenge here is that the right column needs to be 100% of the screen height while scrolling. To achieve thi ...

The Angular-UI-Router version 1.0.11 is cautioning against the use of a class instead of an ID in the jarvis.widget.js file, stating "Warning: It appears you are using a

I recently upgraded my Angular version from 1.4.12 to angular v1.6.6 while using SmartAdmin. After the update, I noticed that an alert started appearing every time I switched between states where JarvisWidget was used. The alert is specifically triggered b ...

What is the method for inserting or passing a city value as a result into the input field with the value attribute set

This code is functioning properly, but the city it generates needs to be registered in #city How can I pass the value #city into an input field? value="cityname" <input id="city" name="input" value="cityname" /> <script> $(document).read ...

Whenever I use Vue JS, instead of receiving my array of objects, I am returned with [__ob__: Observer

Struggling to retrieve data from the database using an API call in my VueJS application. I'm new to VueJS and JavaScript, tested the API with Postman and received the correct JSON response. Current output: [__ob__: Observer] length: 0 __ob__: Observ ...

Delete an entry in a singular mapping in a one-to-one connection [TypeORM]

Is there a way to remove an index from a one-to-one relationship in TypeORM? @OneToOne(() => Customer, { cascade: true }) @JoinColumn({ name: 'customer', referencedColumnName: 'uid' }) customer: Customer I searched the d ...

What is the best way to retrieve a JSON element obtained from a Parse.com query?

I'm encountering difficulties when attempting to access a specific JSON element that I receive in response from a query made into a Parse.com Class. Despite reading through various questions and answers on similar topics, I have yet to find a solutio ...

jQuery not firing keyup event upon deleting the last item

Encountering an unusual issue with the "keyup" event: After entering text into an input field and then deleting it, the final delete keyup event does not register. Sample code: $('#input').on('keyup',function(){ if($(this).val().len ...

Keyboard control of Material UI Checkbox

As we work on developing a web application using react and material ui, accessibility for persons with disabilities is a key consideration. This means ensuring that the web application is operable through keyboard navigation. It's important that user ...

Utilizing imported components to set state in React

In my project, I created a functional component named Age and imported it into another functional component called Signup. This was done in order to dynamically display different divs on a single page based on the authentication status of the user. By sett ...