Utilizing the async pipe and subscribe method in Angular for handling multiple instances of *ngIf conditions

I'm currently experiencing an issue with my Angular setup and I am struggling to identify what the exact problem is. To provide some context before diving into the problem itself:

Within a class called data-service.ts, there exists a method named "getData". Here is the implementation of this method:

getData(): Observable<Data[]> {
let params = new HttpParams();
params = params.append('user_id', this.userId);
return this.http.get<Data[]>('api/data', {
  observe: 'body',
  responseType: 'json',
  params
}).pipe(
    map((response: any[]) => {
      return response.map((s) => ({
        id: s.id,
        userId: s.user_id,
        type: s.type_id,
        ...
      }));
    })
);}

My goal is to retrieve this data and update the view every time a user accesses a specific tab within ngModal. The modal component "modal-component.ts" fetches this data upon clicking the targeted tab, triggering an event using the following code:

getData(evt) {
  this.data$ = this.dataSevice.getData();
}

I am passing the "data$" observable to a child component using an async pipe:

<modal-component>
...
    <app-data-manager [data]="data$ | async"></app-data-manager>
...
</modal-component>

Within the "data-manager", I am utilizing *ngFor on [data], and for each data entry, I am rendering some HTML content. In that HTML, I use *ngIf to determine which template (either first or second) should be rendered.

<div *ngIf="isTrue(dataEntry); then first else second"></div>

The issue at hand: The isTrue method is being invoked multiple times for each dataEntry in the dataset, resulting in numerous calls. I have tried using promises, Take(1) pipe, assigning boolean values during mapping, subscribing to the data, and passing a regular collection instead of leveraging the async pipe. However, I am unable to pinpoint the root cause of this behavior - any assistance would be greatly appreciated. Thank you!

Additional information: When I replace isTrue(dataEntry) with dataEntry.isTrue in *ngIf, the same results persist. I also implemented "OnChanges" in the child component with a console log, where it logs once on the first click and twice on the subsequent clicks, displaying repeated messages.

Answer №1

The issue arises from incorporating a function call within an angular expression, which should be avoided.

Each time Angular's change detection process is triggered, the isTrue() function gets executed potentially multiple times.

Angular cannot anticipate whether the output of isTrue() has changed, necessitating the function's execution upon every change detection cycle.

Consequently, any change detection event across the application (even outside of the app-data-manager component) will trigger the execution of isTrue().

For additional insights on this topic, refer to: https://medium.com/showpad-engineering/why-you-should-never-use-function-calls-in-angular-template-expressions-e1a50f9c0496

An alternate approach involves utilizing properties instead of functions. For scenarios requiring encapsulation of intricate logic, consider creating a custom pipe as demonstrated below.

*ngIf="(dataEntry | isTruePipe); then first else second"></div>

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

Sign out of Google and Facebook accounts using Angular framework

Upon logging in to both Facebook and Google using this package, I am facing an issue with signing out. Even after using the code provided below, I cannot seem to sign out of Google and Facebook: this.authService.signOut(); sessionStorage.clear(); Any as ...

To successfully import files in Sveltekit from locations outside of /src/lib, make sure to include the .ts extension in the import statement

Currently, I am working on writing tests with Playwright within the /tests directory. I want to include some helper functions that can be placed in the /tests/lib/helpers folder. When the import does not specifically have a .ts extension, tests throw a mo ...

Discovering the position of an element within an array and leveraging that position to retrieve a corresponding value from a separate array

const STATE = ["TEXAS","CALIFORNIA","FLORIDA","NEW YORK"] const STATE_CODE = ["TX","CA","FL","NY"] With two arrays provided, the first array is displayed in a dropdown menu. The challenge is to retrieve the corresponding state code from the second array ...

Scrollable Turbo Table experiencing a problem with the PrimeNG filter dropdown

When using PrimeNG Turbo Table, I am facing an issue where the filter dropdown is getting placed inside the scrollable table. The dropdown works perfectly fine without the scrollable table. You can see it in action here. However, when the table is scroll ...

Unauthorized access for POST request in WooCommerce API: 401 error

Let's start by examining the complete code to better understand the issue at hand. Here is the WooCommerce API authentication using the consumer key and secret from the file checkout.ts: this.WooCommerce = WC({ url:"http://localhost/ ...

Is there a way to create an interpolated string using a negative lookahead condition?

When analyzing my code for imports, I will specifically be searching for imports that do not end with -v3. Here are some examples: @ui/components <- this will match @ui/components/forms/field <- this will match @ui/components-v3 ...

If you're not utilizing v-model.lazy, Vue3 Cleave js may encounter functionality issues

I am currently experimenting with cleavejs to format the thousand separator in my input numbers. I've noticed a strange behavior where if I input 1000.123, it displays as 1,000.12 which is the correct format. However, the v-model value remains as 1000 ...

Navigating through Expo with Router v3 tabs, incorporating stack navigation, search functionality, and showcasing prominent titles

I've been working on designing a navigation header similar to the Apple Contacts app, with a large title and search function, but only for the Home Screen. All other tabs should have their own unique settings, like different titles or hidden navigatio ...

Enhance User Experience with Angular Material Autocomplete

I require assistance with implementing an auto-complete field using Angular Materials. Upon page load, a service is utilized to make an API call to a backend node application that communicates with a sandbox API to retrieve a list of supported cities. This ...

The data structure does not match the exact object type

Why isn't this code snippet functioning as expected? It seems that 'beta' has keys of type string and their values are compatible (id is a number type, and temp is also a number type). Additionally, the Record function should make the values ...

Understanding the functionality of imports within modules imported into Angular

I have been scouring through the documentation trying to understand the functionality of the import statement in JavaScript, specifically within the Angular framework. While I grasp the basic concept that it imports modules from other files containing expo ...

Using redux action in the onPaginationChange function instead of setPaginationState in the given example for the TanStack table - is there a way to

Provided this sample Is there a way to utilize by dispatching a redux action rather than using useState - setPaginationState? onPaginationChange: state => dispatch(browseItemModalActions.setPagination(state)) An error is appearing in the console: ...

Encountered an issue with Angular and Ionic 4 when attempting to listen to real-time data: InvalidPipeArgument error was thrown for the AsyncPipe with an empty argument

In my ionic 4 app, I am attempting to implement real-time message updates using angularfire2 and the Firebase Realtime Database. The code snippet is shown below: When running this code, it throws an error: Error: InvalidPipeArgument: '' for pip ...

Visual Studio Code unable to locate source maps for typescript debugging

Looking for some help debugging a basic Hello World TypeScript file. Whenever I try to set a breakpoint, it seems like VS Code is having trouble locating the source map, even though it's saved in the same directory. I'm using Chrome as my browser ...

What steps do I need to take to ensure my TypeScript module in npm can be easily used in a

I recently developed a module that captures keypressed input on a document to detect events from a physical barcode reader acting as a keyboard. You can find the source code here: https://github.com/tii-bruno/physical-barcode-reader-observer The npm mod ...

Creating a Class in REACT

Hello fellow coding enthusiasts, I am facing a minor issue. I am relatively new to REACT and Typescript, which is why I need some assistance with the following code implementation. I require the code to be transformed into a class for reusability purposes ...

What causes the component's constructor to be invoked multiple times instead of being efficiently reused by the router?

I came across this interesting article where the writer discusses how the router reuses components to avoid unnecessary DOM modifications: In order to prevent unnecessary changes to the DOM, the router will reuse components when the parameters of the co ...

When using Angular 2, an error may occur where you receive a message stating that you cannot read the property 'length' of undefined while attempting to call

When creating a component (let's call it A) with the @input decorator to retrieve values from the selector, keep in mind that this component will generate text fields based on the input values specified in the selector. Component A is then utilized in ...

Error: Unable to locate the specified Typescript function

For the source code, please visit https://github.com/zevrant/screeps I am encountering an issue with my implementation of interfaces in TypeScript. When trying to call the implemented interface, I am getting the following error: "TypeError: spawn.memory.t ...

Triggering multiple updates within a single method in Angular will cause the effect or computed function to only be triggered

Upon entering the realm of signals, our team stumbled upon a peculiar issue. Picture a scenario where a component has an effect on a signal which is a public member. In the constructor of the component, certain logic is executed to update the signal value ...