Best Practice for Using *ngIf in Angular (HTML / TypeScript)

In the past, I frequently used Angular's *ngIf directive in my HTML pages:

<p *ngIf="var === true">Test</p>

(for instance)

However, there have been instances where I needed to perform multiple checks within the *ngIf directive on certain pages, sometimes even across multiple tags on the same page:

<p *ngIf="var1 === true && var2 === true && var3 === true && var4 === true && var5 === true && var6 === true && var7 === true && var8 = == true && var9 === true && var10 === true">Test</p>

(for example)

To simplify this complex condition, I decided to refactor it as follows:

<p *ngIf="this.isVarsTrue()">Test</p>

And in my TypeScript file:

isVarsTrue () {
    if (var1 === true && var2 === true && var3 === true && var4 === true && var5 === true && var6 === true && var7 === true && var8 === true && var9 === true && var10 === true) {
      return true;
    } else {
      return false;
    }
  }

Upon further inspection by adding a console log to this method, I noticed that it is being called multiple times (5 times for each action on the page). This made me question whether this approach is considered good practice or not.

I appreciate any insights you may have on this matter. Thank you!

Answer №1

The way Angular's change detection functions is influenced by the use of ChangeDetectionStrategy.Default, which is the default setting for every component (unless modified). While it may not incur significant costs to verify if specific conditions are met (unless dealing with complex logic and high-speed applications), an alternative approach could involve modifying the ChangeDetectionStrategy or storing the condition's outcome in a variable for possible recalculations.

Answer №2

Regarding this particular scenario, I believe it will not have a negative impact on performance.

Nevertheless, to avoid running repetitive code during each render process, I recommend introducing a new component boolean variable that is only updated when any of your multiple variables change. This approach enhances readability and safeguards against unnecessary executions in case the function becomes more intricate.

Answer №3

It was mentioned in a previous comment that using a basic function like the one you provided doesn't significantly impact performance, and it may even be advantageous if it is used in multiple locations. Each event on your screen will trigger these checks whether they are in the HTML or in your TypeScript code. Personally, I try to avoid placing function calls in HTML files (except for specific events like click or change) to prevent any mistakes that could cause my app to lag.

Here are some guidelines on which types of functions I believe are safe/unsafe to call directly from the HTML:

Safe to call from HTML

  • boolean/object/string/number/etc. checks
  • simple if statements

Avoid calling directly from HTML

  • Iterating over an array
  • Observable/Subject/Promise calls
  • Server calls
  • Timeouts/waits

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

Ignoring the NGRX Store selector override during testing appears to be happening

When overriding the selector to return null, the data is still returned as per the override set during initialization. Attempting to use setState did not yield results either. Testing the else condition in the following code block: this.store.pipe(select( ...

Develop a TypeScript Module that consolidates all exports

My Goal with TypeScript Modules I aim to streamline my TypeScript project by creating a module that contains all the necessary class exports. Currently, I find myself using relative import statements in my classes, which can make maintenance challenging i ...

What is the best approach to integrate react-hooks, redux, and typescript seamlessly?

Struggling to seamlessly integrate React-hooks, Redux, and Typescript. It's a never-ending cycle of fixing one error only for another to pop up. Can anyone pinpoint what the root issue might be? Currently facing the following error related to my red ...

The Type '{Property: string, Property2: string} does not match the type Observable<Filters[]>

Here is a method I am trying to use: getFilters(): Observable<Filters[]> { let filters: Observable<Filters[]> = [ { property: "Value", property2: "Value2" }, { property: "Value3", property2: "V ...

Tips for displaying an element for each item chosen in a multi-select box

I currently have a situation where I am rendering for every selected element within my multiselect angular material selectbox. The rendering process functions correctly when I select an element, but the issue arises when I try to deselect one - it just ke ...

Tips for executing multiple asynchronous calls simultaneously within a nested map function

I am facing a scenario where I have an object with nested arrays of objects which in turn contain another set of nested arrays. To validate these structures, I have an asynchronous function that needs to be executed concurrently while awaiting the results ...

Learn How to Implement Styling in Material UI using Styled Components

Utilizing styled-components with MaterialUI integration. Encountering the following error in LoginTextField component and seeking a resolution. Error Message: [ts] Type '{ width: number; }' is missing the following properties from type &apos ...

Angular 6 Encounter: "ReferenceError: alertify is not defined" - Alertify Error Detected

I recently attempted to integrate alertify.js into my project and followed a tutorial at . However, when I clicked a button in my application, I encountered an error that said ReferenceError: alertify is not defined. In order to add alertifyjs css and js ...

How to implement SVG in React with the image source as a parameter?

I've been working on a React component in NextJS that displays an image inside a hexagon. The issue I'm facing is that when I try to use multiple instances of this component with different images in the HexagonWall, all hexagons end up displaying ...

Having trouble retrieving form values in Typescript React, only receiving HTML tag as output

I am having an issue with retrieving the form value to my useRef hook as it returns the HTML tag of the form instead. To solve this, I attempted to specify the type HTMLFormElement inside the chevrons and set null as the initial value for my useRef hook. ...

The interpolated string type is not allowed to be utilized for indexing a record that has the identical type as the key

I'm attempting to utilize an interpolated string form to access a Record type using a key that should match the record's key type. Unfortunately, it doesn't appear to be functioning as expected. Here is a simple example: type TypeOfKey = `c ...

I can't seem to catch my Zod error, even though 'express-async-errors' is already installed. What could be causing this issue?

I've been working on developing an API, but I'm facing issues with setting up a global error controller using Zod. It seems that the global error handler is not being called even though I'm using express-async-errors. Below is my error mana ...

What is the method in TypeScript for defining a property in an interface based on the keys of another property that has an unknown structure?

I recently utilized a module that had the capability to perform a certain task function print(obj, key) { console.log(obj[key]) } print({'test': 'content'}, '/* vs code will show code recommendation when typing */') I am e ...

Tips for utilizing ng-template in various components

Is there a way to display an <ng-template> in different components? For example, let's take the component test with the following structure: test.html <ng-template #content > <p> Hello world </p> </ng-template> test. ...

Choose a specific location on a vehicle illustration within a pop-up window. The image should be partitioned into 6 separate sections

I have a project for my client where they need to choose a car and then indicate where the damage is located on an image, which is divided into 6 sections. I'm struggling to figure out how to achieve this. I initially thought z-index would work, but ...

When deploying, an error is occurring where variables and objects are becoming undefined

I've hit a roadblock while deploying my project on Vercel due to an issue with prerendering. It seems like prerendering is causing my variables/objects to be undefined, which I will later receive from users. Attached below is the screenshot of the bui ...

Creating an RxJS observable stream from an event emitted by a child element in an Angular 2 component template

Currently incorporating Angular 2.0.0-rc.4 alongside RxJS 5.0.0-beta.6. In the midst of exploring various methods for generating observable streams from events, I find myself inundated with choices and would like to gather opinions. Recognizing that there ...

What could be causing the div to be wider than the content inside of it?

I am having an issue creating a webpage with a 20-60-20 flex fill layout. The div in the center, which should occupy 60% of the page, is wider than its content, causing it to appear off-center. https://i.stack.imgur.com/WwCJy.png Here is my home.componen ...

Troubleshooting issues with exporting Excel in Angular 2

Having trouble exporting data in excel format using JExcelApi lib with an Angular 2 frontend and spring mvc backend? When deploying the backend to Tomcat and making a request via browser, the excel file exports correctly. However, when making the same http ...

Exploring Child Types in Typescript and JSX minus the React framework

It seems like there's a missing piece of the puzzle that I can't quite figure out. Despite going through the documentation on JSX in non-React settings, I'm still unable to spot my mistake. Let's examine the following code: /** @jsx pra ...