Full-Stack Filter complete Search (angular)

In this tutorial, I will show you how to do a filter search in Angular application.

1. Get products from the server.

First, we will get our product from the server. The following code sends a get request to the server and gets a response of the product from the server.

 getAllproduct(){
    return this.httpClient.get<{ products: Product[]}>(this.baseurl 
+ '/api/products');
  }

2. Import products from product service to product component

The following code calls the getAllProduct() method in product service and subscribes to products of the Product interface.

ngOnInit() {
    this.productService.getAllproduct().subscribe(res =>{
        this.productsData = res.products;
      }
    );
}

3. Initialize Products

Initialize products in the Product in your chosen component.

initializeItems(){
   this.products = this.productsData;
    }

4. Specify Search property

The following property will be used to bind our search input values to be compared with the product array.

searchProperties = { name: ''};

5. Search Input

In the product template, we will make use of ion search-bar bind input value to search properties name and a change event that spit out the input values.

 <ion-item>
         <ion-searchbar placeholder="search product" type="text"
           [(ngModel)]="searchProperties.name" name="search"
           debounce="500" (ionChange)="getItems()"></ion-searchbar>
  </ion-item>

6. Initialize product in ngOnInit


ngOnInit() {
    this.productService.getAllproduct().subscribe( res =>{
      this.productsData = res.products;

        this.initializeItems();
      }
    );
}

7. The get method

The below code is where the filtering takes place. The get method initialized the product data passing it to the product array. Takes the value from search properties name, trim value to remove white spaces. and does nothing if the value is empty.  filter the product array that meets the specified condition, pass the matched value to the product array.

getItems() {
      // Reset items back t

      this.initializeItems();
      // set val to the value of the searchbar

      const val = this.searchProperties.name;

      // if the value is an empty string don't filter the items
      if (val && val.trim() != '') {
          this.products = this.products.filter((item) => {
          return (item.name.indexOf(val) > -1);
      });
      }
      }

Default image
swagasoft
Articles: 4

Leave a Reply