Hey there! I'm currently working on implementing a search feature in my Angular 14 + Ionic v6 application. The user can search for products using a search field, which triggers an API call. I have three specific scenarios that I need to address:
If the user is on the search page but hasn't entered any text yet, a message below the search input field should show "Please enter at least 3 characters to search...".
In case the user performs a search but no results are found, a message should be displayed stating "Your search did not yield any results...".
Show search results -> THIS WORKS
I'm currently facing an issue with displaying the two additional messages. They both appear simultaneously when they shouldn't. Can you help me identify what might be wrong with my code?
Here is the HTML markup:
<ion-searchbar inputmode="search" [debounce]="1000" placeholder="Search" show-clear-button="focus" (change)="search($event)"></ion-searchbar>
<ion-list>
<ion-item *ngIf="products.length === 0" class="ion-text-center">
<ion-label>
<span class="prod-code"& gt;Enter at least 3 characters to search...</span>
</ion-label>
</ion-item>
<ion-item routerLink="/product/{{produkt.id}}" *ngFor="let produkt of products">
<ion-label>
<span class="prod-code">{{ produkt.product_code }}</span>
<span class="prod-name">{{ produkt.name }}</span>
</ion-label>
</ion-item>
<ion-item *ngIf="products.length === 0" class="ion-text-center">
<ion-label>
<span class="prod-code">Your search did not find any results...</span>
</ion-label>
</ion-item>
</ion-list>
And here is the TypeScript code responsible for the search API call:
import { Component, OnInit } from '@angular/core';
import { SearchService } from '../services/search.service';
import { ToastController } from '@ionic/angular';
@Component({
selector: 'app-search',
templateUrl: './search.page.html',
styleUrls: ['./search.page.scss'],
})
export class SearchPage implements OnInit {
term: string;
products: any = [];
constructor(
private searchService: SearchService,
private toastController: ToastController,
) { }
ngOnInit() {
}
search(event: any) {
console.log('Searched value = ' + event.target.value);
const searchTerm = event.target.value;
if(searchTerm === '') {
return this.products = [];
} else {
this.searchService.searchByTermCall(searchTerm).subscribe(
(data: any) => {
console.log(data.body);
this.products = data.body;
},
error => {
console.log('Error', error);
}
);
}
}
async errorToast(message, position: 'bottom') {
const toast = await this.toastController.create({
message,
duration: 3000,
color: 'danger',
icon: 'close-circle-outline',
position
});
await toast.present();
}
}