Search code examples
angularionic-frameworkangular7ionic4

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 ?


Solution

  • 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>