Home > Back-end >  Angular dropdown bounded to function is being infinitely called
Angular dropdown bounded to function is being infinitely called

Time:08-31

I am using a PrimeNg dropdown and passing its options using a function. However, it is being called infinite number of times. Will this cause an issue with the performance or any other factor, and if so, is there a workaround?

HTML:

<tabset>
    <tab *ngFor="let item of countries" [heading]="item.country">
        <div >
            <label for="state" >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('getting states');
        return this.stateMap.filter(x => x.countryId == countryId)[0]?.states;
    }

CodePudding user response:

You should replace [options]="getStates(item.countryId)" with a pure pipe like `[options]="item.countryId | getStates".

Create a pipe, and add the logic for retrieve the stats inside.

Then, only if item.countryId change the method inside pure pipe is called.

  • Related