Repeated calls to Angular's <img [src]="getImg()"> frequently occur

Can someone help me figure out what's going on here? Recently, I set up a new Angular project and in app.component.html, I have the following code:

<img [src]="getDemoImg()">

In app.component.ts:

getDemoImg(){
  console.log('why so many logs???');
  return 'https://historia.nationalgeographic.com.es/medio/2019/12/11/coliseo-roma_2924b6ae_1280x720.jpg'
}

The issue is that the console.log message is appearing four times, indicating that the function is being called repeatedly. Any insights into what could be causing this?

Here is a link to a reproducible example: https://stackblitz.com/edit/angular-ivy-d5hdmo?file=src%2Fapp%2Fapp.component.html

Answer №1

It's important to note that when change detection runs in your HTML, all functions will be called automatically. The framework checks for any changes that could affect the variables in your code.

Calling functions directly in HTML can have consequences, especially if they are time-consuming or involve making HTTP requests. This can slow down your application and lead to excessive data retrieval from databases.

If you want to prevent automatic change detection on a component, you can use the OnPush strategy as shown below:

@Component({
    selector: 'my-component',
    changeDetection: ChangeDetectionStrategy.OnPush,
    template: ...
})
export class MyComponent {

With this strategy, your HTML will only update when change detection is explicitly triggered or when an @Input() variable is modified.

constructor(private changeDetectorRef: ChangeDetectorRef) {}

refresh() {
    this.changeDetectorRef.detectChanges();
}

For more information on change detection, check out these resources:

Example with the OnPush strategy

How does Angular 2 change detection really work?

The ultimate guide for Angular change detection

Answer №2

To achieve optimal results, it is recommended to employ a variable for binding the src attribute or any other attribute, and subsequently update the variable as necessary.

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

The Yeoman/Grunt-usemin is failing to update the index.html file even after adding new JavaScript code

As I work on developing a web app using Yeoman and the Angular generator on Windows 7, I go through the process of running 'yo angular' followed by 'grunt' to build the app for deployment. The index.html file in the dist folder gets upd ...

Tips for real-time editing a class or functional component in Storybook

Hey there, I am currently utilizing the storybook/react library to generate stories of my components. Everything has been going smoothly so far. I have followed the guide on https://www.learnstorybook.com/react/en/get-started and added stories on the left ...

Replacing one <div> with another <div> using a clickable link within the divs

In one of my web pages, there is a div that I'll refer to as div1. Within this div, there is a link called 'Link1'. My goal is to click on Link1, triggering the replacement of div1 with div2. Inside div2 there will be another link, let&apos ...

The Battle of Identifiers: Named Functions against Anonymous Functions in TypeScript

When it comes to performance and performance alone, which option is superior? 1) function GameLoop() { // Performing complex calculations requestAnimationFrame(GameLoop); } requestAnimationFrame(GameLoop); 2) function GameLoop() { // ...

Partial data is being received from the Ajax call

I currently have a textarea and a button on my webpage <textarea id="xxx" class="myTextArea" name="Text1" cols="40" rows="15">@ViewData["translation"]</textarea> <input type="button" id="convert-btn" class="btn btn-primary" value="Convert t ...

When utilizing jQuery to add a <li> element, it suddenly vanishes

? http://jsfiddle.net/AGinther/Ysq4a/ I'm encountering an issue where, upon submitting input, a list item should be created with the content from the text field. Strangely, it briefly appears on my website but not on the fiddle, and no text is appen ...

Failure of AJAX to transmit variable to PHP script

I am relatively new to PHP and currently working on the dashboard page of a website where an administrator can view all existing admins. Each admin's row has a button that is supposed to check their privileges, such as access to article editing and cl ...

Upgrading Angular causes issues with fileReplacements not functioning properly for assets

Since upgrading Angular, I have encountered an issue where fileReplacements no longer work with assets. Here is the code snippet that I am using: "fileReplacements": [ { "replace": "src/assets/scss/x.scss", ...

Communicating between different components in Angular 11 using a service to share data

In my Angular 11 project, componentB has multiple methods that need to be called from componentA. Although I am aware that transferring these methods to a service would be the proper solution, it requires extensive effort which I want to avoid for now. In ...

Arranging Pipe Methods in RxJS/Observable for Optimal Functionality

In the class Some, there is a method called run that returns an Observable and contains a pipe within itself. Another pipe is used when executing the run method. import { of } from 'rxjs'; import { map, tap, delay } from 'rxjs/operators&ap ...

Can someone assist me in figuring out how to solve selecting multiple radio buttons at once

<script type="text/javascript"> let x = "1.html"; let y = "2.html"; function redirectPage(form){ for(let i=0; i<form.length; i++) { if(form.answerq[i].checked && form.answerw[i].checked && f ...

When attempting to navigate to a controller using Express.Router and Passport, encountering an undefined error with req.url.indexOf('?')

The statement "var search = 1 + req.url.indexOf('?');" throws an error indicating that it is undefined. I am currently working on creating a login/registration page using passportjs on my angular frontend. When attempting to make a post request t ...

Unable to click on element at specific location

Hey there, I'm encountering an issue trying to click on a specific element and it's not working. I keep receiving the following error message: ElementClickInterceptedException: Message: element click intercepted: Element ... is not clickable at ...

Setting up a Form submit button in Angular/TypeScript that waits for a service call to finish before submission

I have been working on setting up a form submission process where a field within the form is connected to its own service in the application. My goal is to have the submit button trigger the service call for that specific field, wait for it to complete suc ...

Unable to add or publish text in CKEditor

In my ASP.NET MVC application, I am struggling to post the updated value from a CKEditor in a textarea. Here is the code snippet: <textarea name="Description" id="Description" rows="10" cols="80"> This is my textarea to be replaced with CKEditor ...

Navigating to a URL parameter outside of the <router-outlet>

Currently, I am developing a simulated e-commerce platform using Angular 11. The structure of my app.component.html file is outlined below: <mat-toolbar> <mat-toolbar-row> <!-- Various buttons and links --> <button *ngIf=&quo ...

Utilizing a refreshed array of elements within a component directive

When working within a view, I am utilizing ng-repeat inside a directive to iterate over an array of objects from my controller. However, as the objects in the array undergo value changes, I encounter a dilemma when transitioning to a new instance of the sa ...

Entering the appropriate value into an object's property accurately

I am currently facing an issue with typing the value needed to be inserted into an object's property. Please refer below. interface SliceStateType { TrptLimit: number; TrptOffset: number; someString: string; someBool:boolean; } inter ...

The parameter value in Angular routes is substituted with the parameter name in the AuthGuard's canLoad method

Within my AuthGuardService, I have a function called canLoad that accepts a parameter of type Route. In this function, I set the authentication redirect URL to the path property of the Route parameter. An issue arises when the path contains a route parame ...

How to retrieve data from a JSON file in Angular 2 using the http get

I am encountering an issue while trying to access a json file using http get. The error message I receive is as follows: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterable ...