Multiple triggers occur when custom component properties are bound

Upon using a custom component with an input property where a function is bound to it, I have observed that the function gets called multiple times.

For example:

<some-tag [random-input]="randomFunction()"></some-tag>

And in the class:

private randomFunction() {
    console.log('Called!');
    return true
}

Running a simple code snippet like this results in several 'Called!' logs appearing in the console. In my project, the randomFunction makes a call to the database, which can be quite bothersome.

Is there anyone who knows why this behavior occurs?

Answer №1

Angular constantly checks for updated values in every cycle, leading to multiple messages in the log.

To avoid this issue, it is not recommended to have TypeScript functions as inputs in a component.

One solution is to make a call to the server/database in the constructor, OnInit, or OnChanges lifecycle hooks, store the result in a local variable, and then use that variable as an input for the component. An example of this approach can be seen below:

export class MyComp {
   dbResult: any;

   constructor(http: HttpClient) {
     http.get('/my/api/call').subscribe(result => {
       this.dbResult = result;
     });
   }
   ....
}

..and in HTML:

<some-tag [random-input]="dbResult"></some-tag>

It's worth noting that marking the function as private may cause issues during production build.

Answer №2

For Angular to successfully update the value within the component, it must first verify if any changes have occurred.

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

Data input tag fails to upload

I'm currently working on an app that aims to upload all data from a hard drive into an array. The structure consists of a main folder with subfolders, and my goal is to extract the names of all subfolders and store them in the array. However, I'v ...

Using React in ES5 to create a button that triggers two separate functions with a

I have encountered an issue with two React classes that both contain a render function returning forms with buttons. In class A, I had to import class B in order to use the form from class B. The problem: Whenever I click the inner button, the outer butto ...

When the page is refreshed, the route fails to load the data

My Vue.JS website is quite simple, utilizing VueX and Vue-Router. I have defined two routes: '#/' and '#/account/' These routes are filled with components from .vue files, loaded dynamically upon page load using http-vue-loader (to avo ...

The model does not align with the body request, yet it is somehow still operational

My programming concept: class User { username: string; password: string; } Implementation of my function: const userList = []; function addUser(newUser: User) { userList.push(newUser); } Integration with Express router: router.post('/user ...

What is the best way to utilize the "useRouter" function to extract parameters from the URL within the getServerSideProps() method in Next.js?

How can I access the URL parameters within the getServerSideProps() method? Below is the snippet of my code. The objective of my code is to extract parameters from the URL, fetch data from the API, and render it on the front end. import { useRouter } from ...

What is the best way to compare a JSON object and a string in JavaScript?

Currently, I am working on developing the website layout for . Most of the data retrieval and display have been successful so far. However, when attempting to filter my search results to show only stop names associated with Subways, I encountered some err ...

Storing data or a page in a list within a React Native application

As a newcomer to React Native, I'm facing an issue. I have two pages called rockSetting.js and myFavoriteSetting.js. In the rockSetting page, I want to implement an onButtonPress function that will generate a list in the myFavoriteSettings page with ...

Jquery assigns the value of the last output to a variable

When it comes to sending comments to a database, I have encountered an issue with my code involving jQuery and AJAX. <script type="text/javascript"> $(document).ready(function() { $('#comm1').keypress(function(event) { ...

Incorporate Thymeleaf's HTML using the powerful JavaScript framework, jQuery

I am facing an issue where the Thymeleaf rendered HTML code is not being displayed by the Browser when I try to insert it using JavaScript. $('<span [[$ th:text#{some.property.key}]] id="counter" class="UI-modern"> </ ...

The Jquery code encountered an issue where it was unable to access the property 'length' of an undefined

My goal is to submit a form using jQuery and AJAX, which includes file upload functionality. The challenge I'm facing is that the forms are dynamically created, so I need to identify which form was clicked and retrieve its input values. $(document).r ...

bootstrap thumbnail displayed without a border

I have decided to incorporate Bootstrap into my latest project: <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS ...

Ajax operates by fetching data from a database without requiring large files to be retrieved

Every time I try to retrieve a file larger than 0.5MB from the SQL database using AJAX, an error occurs. What am I doing wrong here? $(document).ready(function () { loadFileData(); }); function loadFileData() { $.ajax({ type: "GET", ...

Angular command not recognized by the system

I've been attempting to set up angular on my computer, but I'm having trouble locating the ng command. I've experimented with aliasing, modifying the path variable, removing the angular package, and updating node and npm. My suspicion is th ...

insert <asp:linkbutton> dynamically

I have a question regarding ASP: I am receiving a list of IDs from the server on my webpage. Can I display this list in a div below an ASP.NET control? div_containing_link += "" If not, is there another way to achieve this? For example, I want to displ ...

The page is not responding after closing the modal dialog

My web application is built using Spring Boot for the backend and Thymeleaf for the front end. The app displays all available groups for users to review. When a user clicks on a group, the documents within that group are listed in a tabular form. Clicking ...

Clicking on an element will remove a class and unselect an input using JQuery

Trying to achieve a functionality where clicking on a list item with a radio button input selects it, but clicking again deselects it. The issue is despite various attempts, nothing seems to work properly. function setupToptions() { if ($('ul.top ...

A guide on using JavaScript to obtain the original calculation for a specific equation once a checkbox has been unchecked

I am facing a scenario where I have two input fields. One should display the value of Quantity, and the other should display the value of Price. The first input, which is for quantity and of type number, has the disabled attribute. However, upon checking a ...

Determine the number of lines present in a textarea

Is there a way to use JavaScript to determine the number of lines in a textarea without relying on the rows attribute? For example, in this scenario, I would expect to get 4 lines. <textarea rows="4">Long text here foo bar lorem ipsum Long text he ...

AJAX success object encounters an uncaught type error

After successfully executing one of my AJAX Posts, there is a logical test with the returned "data" object. Surprisingly, upon page load, JavaScript throws an uncaught type error stating that it cannot read a property of undefined on this line: success: f ...

Struggling with a non-functional jQuery navigation tab onclick feature

Within my Django template, I am working with a series of nav-tabs that are being populated by a context variable: <div class="content-object"> <ul class="nav nav-tabs nav-fill" id="object_tab" role="tablist"> {% for object in object_ ...