0

We're using Angular together with Bootstrap. We created a button group like

<div class="input-group-append">
  <div class="btn-group" role="group">
    <button class="btn btn-sm btn-outline-secondary"
      [(ngModel)]="currentDisplayedList"
      (ngModelChange)="changeFilter()"
      btnRadio="subscribed" >subscribed</button>
    <button class="btn btn-sm btn-outline-secondary"
      [(ngModel)]="currentDisplayedList"
      (ngModelChange)="changeFilter()"
      btnRadio="available">available</button>
    <button *ngIf="getPerm()?.canDeleteRss()"
      class="btn btn-sm btn-outline-secondary"
      [(ngModel)]="currentDisplayedList"
      (ngModelChange)="changeFilter()"
      btnRadio="deleted">deleted</button>
  </div>
</div>

enter image description here

After some different upgrades in Angular the major problem is the init of the component. At the init the ngModelChangeis fired three times in a row - for each button separately. Which triggers the function changeFilter() and performs all the actions (retrieving data from DB) multiple times.

Is there a 'simple' way to prevent this and call it only once?

2
  • Just throwing out an idea. One way is to moved the changeFilter() code into a subject and put a debounceTime 500ms on it. Commented Jul 22, 2021 at 14:12
  • Yeah... might be an idea.... But how would you do it properly? Commented Jul 22, 2021 at 15:07

1 Answer 1

1

First create a Subject, add a debounceTime of 500ms and subscribe to it.

var onChangeFilter$ = new Subject();

var subscription = onChangeFilter$.pipe(debounceTime(500)).subscribe(_=>{
   this.onChangeFilter();
});

Then rewrite the ngModelChange to simply call next() on the subject.

(ngModelChange)="triggerChangeFilter()"

triggerChangeFilter(){
    this.onChangeFilter$.next();
}

Make sure to destroy the subscription on ngDestroy

this.subscription.unsubscribe();
Sign up to request clarification or add additional context in comments.

2 Comments

I appreciate your effort. The main problem with this approach is that the debounceTime causes a change in the init sequence and than I cannot any longer distinguish between user interaction and init-procedure :-/ So, your approach works but not for the init-phase!
Do you have currentDisplayList as @input, and an api call in changeFilter() which also sets the currentDisplayList? Could you create a stackblitz sample?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.