Taken to top of content when using ngFor inside an ngIf

40 Views Asked by At

I have a reorder section inside a food ordering app, the orders are paginated from backend and are loaded using ion-inifite-scroll. I have two buttons which show me delivered orders and upcoming orders. The data for both sections is displayed using *ngFor which is inside an *ngIf. When scrolled to the bottom of the section ion-infinite-scroll pushes more data into the array used in the ngFor, but as soon as the data is pushed I am taken to the top of content.

HTML code:

<ng-content>

<!-- buttons -->
  <button (click)="pastOrDelivered(false)">
    Upcoming Orders
  </button>

  <button (click)="pastOrDelivered(true)">
    Delivered Orders
  </button>

<!-- upcoming orders -->
  <div *ngIf="showUpcoming">
    <div *ngFor="let order of upcoming; let i=index;">
      <div class="item-card item-card-bottom">
        <h4>upcoming data</h4>
      </div>
    </div>
  </div>

<!-- delivered orders -->
  <div *ngIf="showDelivered">
    <div *ngFor="let order of delivered; let i=index;">
      <div class="item-card item-card-bottom">
        <h4>delivered data</h4>
      </div>
    </div>
  </div>

<ion-infinite-scroll threshold="30%" position="bottom" [disabled]="!shouldGetOrders" (ionInfinite)="onIonInfinite($event)">
  <ion-infinite-scroll-content loadingSpinner=""></ion-infinite-scroll-content>
</ion-infinite-scroll>

</ng-content>


Typescript:

class OrderHistoryPage {
  upcoming: any = [];
  orders: any = [];
  deliveredOrders: any[] = [];
  showDelivered: boolean = false; 
  showUpcoming: boolean = true;
  offset = 0;
  records = 10;
  shouldGetOrders = true;

  async ionViewDidEnter() {
    this.pastOrDelivered(true);
    this.getOrders();
  }

  async getOrders() {
    this.userAPI.getOrderHistory(this.offset, this.records)
    .subscribe((orders: any) => {
      if(orders.total >= this.records) {
        this.offset += this.records;
      } else {
        this.shouldGetOrders = false;
      }
      
      this.orders = orders.orders;

      this.orders.forEach( order => {
        if (order.deliveryStatus != 'DELIVERED' && order.deliveryStatus != 'CANCELLED') {
          this.upcoming.push(order)
        } else if (order.deliveryStatus == 'DELIVERED' || order.deliveryStatus == 'CANCELLED') {
          this.deliveredOrders.push(order)
        }
      });
      }, err => {});
  }

  onIonInfinite(ev) {
    if(this.shouldGetOrders === true) {
      this.getOrders();
      setTimeout(() => {
        (ev as InfiniteScrollCustomEvent).target.complete();
      }, 500);
    }
  }

  pastOrDelivered(params) {
    this.showDelivered = params
    this.showUpcoming = !params
  }

}

I have confirmed that this happens because of ngIf in which I have wrapped the ngFor div. I have tried to replace the ngIf with [style.display]="showUpcoming ? 'block' : 'none'". But that did not work either.

0

There are 0 best solutions below