Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ngOnChanges is calling up multiple times

I have generated multiple ion-slides using ngFor, and inserted a component there. It is calling ngOnChanges multiple time. I want it should call only once, so that I can call my api.

I have tried using multiple angular lifecycle hooks.

This is how I created my slides, menu has 19 elements

<ion-slides #slides [options]="slideOpts" (ionSlideDidChange)="slideChanged($event)">
<ion-slide *ngFor="let i of menu; let j = index">
  <h1>{{ i.name }}</h1>
  <app-homenews [categoryId]="currentCategoryId" ></app-homenews>
</ion-slide>
</ion-slides>

This is how we are making change detection

@Input() categoryId: number;

ngOnChanges(changes: SimpleChanges) {
   let chg = changes['categoryId'];
   console.log(chg.currentValue);
} 

I want it to be called only once, it is calling 19 times now.

Can I use rxjs here ?

like image 344
Abhishek Soni Avatar asked Nov 09 '25 03:11

Abhishek Soni


1 Answers

ngOnChanges runs when there is change in value of Input variable comes from a template binding.So triggering it multiple times is a normal behavior.If you want to execute some code only once you can use it like this

@Input() isFirstRun;
ngOnChanges(changes: SimpleChanges) {
  if(this.isFirstRun){
     let chg = changes['categoryId'];
     console.log(chg.currentValue);
  }
}

<ion-slide *ngFor="let i of menu; let j = index">
  <h1>{{ i.name }}</h1>
  <app-homenews [isFirstRun]="j===0?true:false" [categoryId]="currentCategoryId" ></app-homenews>
</ion-slide>
like image 191
sreejithsdev Avatar answered Nov 11 '25 02:11

sreejithsdev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!