The never-ending cycle of an Angular dropdown linked to a function being repeatedly invoked

I am currently working with a PrimeNg dropdown that is fetching its options through a function call. However, I have noticed that this function is being called an excessive number of times. Could this potentially impact the performance or any other aspect? If so, are there any solutions to address this issue?

HTML:

<tabset>
    <tab *ngFor="let item of countries" [heading]="item.country">
        <div class="mb-5 col-md-6">
            <label for="state" class="col-lg-12 form-label">State</label>
            <p-dropdown [options]="getStates(item.countryId)" name="stateId" placeholder="Select State" optionLabel="name" optionValue="id" [showClear]="true"> </p-dropdown>
        </div>                           
    </tab>
</tabset> 

TS:

    getStates(countryId: number): StateDto[] {
        console.log('fetching states');
        return this.stateMap.filter(x => x.countryId == countryId)[0]?.states;
    }

Answer №1

To improve performance, consider switching from

[options]="getStates(item.countryId)"
to using a pure pipe like `[options]="item.countryId | getStates".

Develop a custom pipe and include the necessary logic to retrieve the stats.

By implementing this change, the method inside the pure pipe will only be called when item.countryId is modified.

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

In TypeScript, it can be challenging to determine the equality between a value and an enum

I am encountering an issue with my simple code: enum Color { BLUE, RED } class Brush { color: Color constructor(values) { this.color = values.color } } let JSON_RESPONSE = `{"color": "BLUE"}` let brush = new Brush(JSON.parse(JSON ...

When using Angular to send a request body containing IFormFile to an ASP.NET Core Web API, the properties are unexpectedly null

I am facing an issue with sending a request body as an object from Angular to ASP.NET Core Web API. All the properties are coming up as null except for ID. Here is the structure of my Web API: public class Book { public int BookID { get; set; } pu ...

TypeScript async function that returns a Promise using jQuery

Currently, I am facing a challenge in building an MVC controller in TypeScript as I am struggling to make my async method return a deferred promise. Here is the signature of my function: static async GetMatches(input: string, loc?: LatLng):JQueryPromise& ...

The View does not get updated by Angular's *ngFor directive

When I modify the Array of servers from outside the class declaration, the View/HTML component does not update accordingly. However, when I perform the same modification from inside the class, it works fine. Both functions successfully update the servers A ...

Incorrect Node.js version identified

I have been facing a challenge trying to integrate my projects developed with Spring and Angular using Maven. The issue arises with the Node.js version: [ERROR] Node.js version v8.11.3 detected. [ERROR] The Angular CLI requires a minimum Node.js version of ...

What is the best way to assign an HTML string to the DOM and connect it with an object?

In my angular HTML component template, I have the following markup: <div *ngIf="htmlTemplate && jsonObj" [innerHTML]="htmlTemplate"></div> The jsonObj variable is retrieved from an endpoint and looks like this: { fi ...

React Typescript does not support the use of React-Router

I'm currently working on a React app that utilizes Typescript. The React version is set to "react": "^16.9.0", and the React-Router version is "react-router-dom": "^5.1.2". Within my App.tsx file, the structure looks like this: const App: React.FC ...

Angular4: Automatically disable button after it is clicked within ngFor loop

I am facing the issue of disabling a <button> in an ngFor loop after it has been clicked by the user. Each button corresponds to an element in the loop, so I need to distinguish them using separate boolean values. Below is a snippet of the HTML code ...

Encountering a module not found error when attempting to mock components in Jest unit tests using TypeScript within a Node.js

I'm currently in the process of incorporating Jest unit testing into my TypeScript-written Node.js application. However, I've hit a snag when it comes to mocking certain elements. The specific error I'm encountering can be seen below: https ...

Discover the process of retrieving all workday dates using Angular

Currently, I am working on a project in Angular that involves allowing employees to record their work hours. However, I am facing a challenge in figuring out how to gather all the work dates and store them in an array. Here is what I have attempted so fa ...

I'm having trouble viewing anything on my localhost with Angular app using Docker

I recently attempted to dockerize an Angular application and encountered some issues. I experimented with two different Dockerfiles in an attempt to resolve the problem but was unsuccessful. The first Dockerfile I tried is as follows: FROM node:latest as n ...

Query executed but no results returned

Currently, I am practicing GQL and facing an issue when trying to display data in the Playground. I am attempting to access the jsonplaceholder API to fetch all posts and show them, but encountering the following error: Error: GRAPHQL_FORMAT_ERROR: Expec ...

What is the reason behind eslint not permitting the rule option @typescript-eslint/consistent-type-imports?

Upon implementing the eslint rule, I configured it like this. module.exports = { rules: { "@typescript-eslint/consistent-type-imports": [ "error", { fixStyle: "inline-type-imports" ...

What is the best way to take any constructor type and transform it into a function type that can take the same arguments?

In the code snippet below, a class is created with a constructor that takes an argument of a generic type. This argument determines the type of the parameter received by the second argument. In this case, the first parameter sets the callback function&apos ...

Error in Typescript: The type 'string' cannot be assigned to the type '"allName" | `allName.${number}.nestedArray`' within the react hook form

Currently, I am tackling the react hook form with typescript and facing a challenge with my data structure which involves arrays within an array. To address this, I decided to implement the useFieldArray functionality. allName: [ { name: "us ...

Utilizing Router Outlet in Angular to Access API Data

I've encountered an issue where I can't pass parent data from the ngOnInit route params to my child component, user-seminar. After some research and searching on Google, I found a solution involving services. To address this problem, I modified ...

Vue component prop values are not properly recognized by Typescript

Below is a Vue component I have created for a generic sidebar that can be used multiple times with different data: <template> <div> <h5>{{ title }}</h5> <div v-for="prop of data" :key="prop.id"> ...

Selecting ion-tabs causes the margin-top of scroll-content to be destroyed

Check out the Stackblitz Demo I'm encountering a major issue with the Navigation of Tabs. On my main page (without Tabs), there are simple buttons that pass different navparams to pre-select a specific tab. If you take a look at the demo and click t ...

Stop modal from closing in the presence of an error

My approach involves using a generic method where, upon adding a food item, a modal window with a form opens for the user to input their details. However, since backend validation for duplicate items can only be retrieved after the API call completes. I w ...

Tips For Implementing Pagination in Laravel 5.8 with Angular 8

Encountering issues when trying to retrieve the next set of results from the database using Laravel pagination. The results obtained are as follows from the route: api/getMerchants { "merchants": { "current_page": 1, "data": [], // con ...