3

When I type in text to search something, displaying one character in text is very slow. What is the problem ? I have display 50 products with ngFor as below , if I display more than 50 products 100 or 150 typing in text is more slow. what should I do to fix this problem ?

<div class="width_products  products-animation " *ngFor="let product of productsService.products ; trackBy: $index"  [ngClass]="{ 'width_products_open_menu':productsService.status_menu  }" >
  <span class="each_width_product" >
    <div  class="title_products more_detail_product" (click)="set_router({ path:product['company'].company_name+'/'+product.product_title , data:product.product_id , relative:true })">
      {{product.product_title }}
      <span class="glyphicon glyphicon-chevron-down"></span><br>
      <div class=' glyphicon glyphicon-time'></div> {{product.product_date}}
    </div>
    <div class="image_product_primary " (click)="set_router({ path:product['company'].company_name+'/'+product.product_title , data:product.product_id , relative:true })">
      <img class="image_product" src="../../assets/images/products_image/{{product.product_image}}">
    </div>
    <button  (click)="product.product_in_wishList='true'; productsService.add_wish_list( product )" mat-button class="wish_list  notCloseDropdawnFavorite notCloseDropdawnCard">
      <span class="write_add_wish">{{dataservices.language.add_wishlist}}</span>
      <mat-icon *ngIf="product.product_in_wishList == 'false' " class="notCloseDropdawnFavorite notCloseDropdawnCard">favorite_border</mat-icon>
      <mat-icon  *ngIf="product.product_in_wishList == 'true' " class="hearts_div_hover notCloseDropdawnFavorite notCloseDropdawnCard">favorite</mat-icon>
    </button>
    <div class="footer_products">
      <span matTooltip="Views!">
        <div class="button_footer_products">
          <span class="glyphicon glyphicon-eye-open icon_eye"></span>
          <div class="both_write ">
            12889
          </div>
        </div>
      </span>
      <span matTooltip="Add to your card"  class="notCloseDropdawnCard notCloseDropdawnFavorite " (click)="product.product_in_cartList='true'; productsService.add_cart_list( product )">
        <div class="button_footer_products">
          <span *ngIf="product.product_in_cartList=='false'" class="glyphicon glyphicon-plus icon_eye notCloseDropdawnCard notCloseDropdawnFavorite" ></span>
          <span *ngIf="product.product_in_cartList=='true'" class="glyphicon glyphicon-ok icon_eye notCloseDropdawnCard notCloseDropdawnFavorite" ></span>
          <div class="both_write ">
            Cart
          </div>
        </div>
      </span>
      <span matTooltip="See Details!">
        <div (click)="set_router({ path:product['company'].company_name+'/'+product.product_title , data:product.product_id , relative:true })" class="button_footer_products" >
          <span class=" glyphicon glyphicon-option-horizontal icon_eye"></span>
          <div class="both_write ">
            More
          </div>
        </div>
      </span>
    </div>
    <div class="prise_products">
      Price:<del>$2500</del> $3500
    </div>
    <div class="plus_height"></div>
  </span>
</div>

In header component I have a input type text as below :

<input type="text" class="kerkim"  name="search" [(ngModel)]="typing_search" placeholder=" 
         {{dataservices.language.searchproducts}}">
Brett DeWoody
  • 59,771
  • 29
  • 135
  • 184
Klodian
  • 633
  • 6
  • 18
  • So. Can you show the whole code. By now someone can only guess what is happening. I guess the typed value in your input is used to filter the product list? But how is it done by now? – David Ibl Mar 25 '18 at 09:30
  • until now is only this that i shared here i am not to send request in server yet to get search products , but ngFor above is to display some products is not for search Products . the problem is when i display products in the dom typing in text in slow , if i not display any product it work well. – Klodian Mar 25 '18 at 09:49
  • Refer: https://stackoverflow.com/questions/49787872/deep-troubling-situation-with-angular-5-and-slow-typing-into-input-boxes – Nilam Oct 17 '19 at 04:38

2 Answers2

2

Debouce effect, e.g. do not run search immediately.

class Coponent {

  private _timeoutId: number;

  //to be called on search text changed
  search(){
    clearTimeout(this._timeoutId);

    this._timeoutId = setTimeout(() => {
      //do search stuff
    }, 500) //play with delay
  }
}

Cache prev results using search keyword. When kyeword changes like so ["k","ke","key"] you do not need to refilter whole array.

class Search {

  private _keywordChanges:string[] = [];
  private _prevFilterResults: any[] = [];
  private _allData: any[] = [];


  search(keyword:string){
    let prevKeyword = this.getPrevKeyword(),
      toBeFiltered: any[];
    if(keyword.match(keyword)){ //if it was "ke" and now it is "key"
      //filter prev results only
      toBeFiltered = this._prevFilterResults;
    } else  {
      //filter prev results or even make cache for keyword
      toBeFiltered = this._allData;
    }

    let results = toBeFiltered.filter(() => {});
    this._prevFilterResults = results;
  }

  private getPrevKeyword(){
    return this._keywordChanges[this._keywordChanges.length - 1];
  }

Use for with break instead of Array.filter(), in some cases it may be helpfull. For example you have sorted array ["a","apple","b","banana"] and keyword "a".

function search(array:any[], keyword:string) {
  //so
  let results = [];
  for(let i = 0; i < array.length; i++){
    let item = array[i];
    if(item.toString().startsWith(keyword)){
      results.push(item);
    } else {
      break; //as b and banana left
    }
  }
  return results;
}

Take a look at binary search. How to implement binary search in JavaScript and hash table Hash table runtime complexity (insert, search and delete)

Vayrex
  • 1,417
  • 1
  • 11
  • 13
0

From my issue: every input field is slow due to many data. so i add "changeDetection: ChangeDetectionStrategy.OnPush" at where data reloaded, then everything work normal.

@Component({
  selector: 'app-app-item',

  templateUrl: './app-item.component.html',

  styleUrls: ['./app-item.component.css'],

  changeDetection: ChangeDetectionStrategy.OnPush,

})
Laoti Sok
  • 1
  • 2