Angular displays various divs depending on the search query entered or when there is no input provided

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:

  1. 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...".

  2. 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...".

  3. 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();
  }

}

Answer №1

If your array of products is undefined at the start, you can utilize nested ngIf. However, if it is defined, you will need to adjust the logic of the first ngIf based on the value in the search bar.

<ion-searchbar inputmode="search" [debounce]="1000" placeholder="Search" show-clear-button="focus" (change)="search($event)"></ion-searchbar>
<ion-list>
   <ion-item *ngIf="!products; else searched" class="ion-text-center">
      <!-- Please enter at least 3 characters.. -->
   </ion-item>
   <ng-template #searched>
      <ion-item *ngIf="products.length !== 0; else emptyList" class="ion-text-center">
         <!-- Display products using ngFor.. -->
      </ion-item>
      <ng-template #emptyList>
         <!-- No results found.. -->
      </ng-template>
   </ng-template>
</ion-list>

Answer №2

If you want to determine whether the user has performed a search in order to decide whether to display the search results or an error message, follow these steps:

<ion-item *ngIf="products.length === 0 && searchbar.value.length >= 3" class="ion-text-center">
      <ion-label>
        <span class="prod-code">Please enter at least 3 characters to perform a search...</span>
      </ion-label>
</ion-item>

To show an error message when the search term is less than or equal to 3 characters, simply add searchbar.value.length <= 3 to the existing *ngIf condition.

Keep in mind that you need to assign a template reference to the searchbar element for this functionality to work correctly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve the current date in the format of dd/mm/yyyy using AJAX request

var currentDate = new Date(); var todayDate = currentDate.getDate() + '/' + monthNames[currentDate.getMonth()] + '/' + currentDate.getFullYear(); This is my current date retrieval method. It works well but has a minor issue. For to ...

The search functionality in Select2 is unresponsive when using Bootstrap 5

I am struggling with clicking on the search input dropdown. I have already searched online and found that this is a common issue with select2 in combination with bootstrap3 or bootstrap4. However, with bootstrap5 it seems to be a bit different (I had succe ...

JavaScript - Capture the Values of Input Fields Upon Enter Key Press

Here's the input I have: <input class="form-control" id="unique-ar-array" type="text" name="unique-ar-array" value="" placeholder="Enter a keyword and press return to add items to the array"> And this is my JavaScript code: var uniqueRowsArr ...

Creating a custom type in Typescript using a function for testing purposes

I have been exploring ways to limit my search capabilities to specific criteria. Let's say I have a model and some data like the following: interface UserModel { _id: string; username: string; party: UserPartyModel; } interface UserParty ...

After executing the command ng build --configuration=production, only the assets folder will be found in the dist directory

As a beginner in Azure, I am trying to deploy an Angular application to Azure using Visual Studio Code. I found a tutorial at https://www.youtube.com/watch?v=u_CRppLcC9k which was quite helpful. However, after running the command ng build --configuration=p ...

What is the process for adding a marker to an Angular Google Map using the autocomplete feature?

Can anyone help me with adding a marker on Google Angular Map using autocomplete search? I am able to retrieve the location in terms of latitude and longitude, but there seems to be an issue with adding the marker. Please review my code below: Controller ...

Error in Angular 8: Module loading from "url" has been intercepted due to an unsupported MIME type ("text/html") being blocked

I have developed an application using Angular 8 and Node 12. When I try to open a new tab or reload the page after building Angular 8, I encounter an issue for which I have extensively searched online but found no solution. In the Firefox console, the er ...

The Javascript countdown feature may experience issues on Safari and IE browsers

Why does this function work in Chrome, but not on IE or Safari? function countdown(){ var dDay = new Date().getUTCDate() + 1; var dMonth = new Date().getUTCMonth() + 1; var dYear = new Date().getUTCFullYear(); var BigDay = new Date(dYear+ ...

A single iteration is all that a for loop in Javascript will complete

I've been working on some code and I'm a bit puzzled by why the for loop seems to only run once, both inner and outer. Even though nodeList.length and innerNodeList.length are showing the correct values when I use alert messages. It's strang ...

Position the Bootstrip 4 tooltip to automatically display on the right side

In order to customize the placement of my tooltip on desktop, I have opted for having it positioned on the right side of the elements. While this choice aligns well with my design preferences, it has presented a challenge when viewing the page on smaller s ...

jQuery Refuses to Perform Animation

I'm facing an issue with animating a specific element using jQuery while scrolling down the page. My goal is to change the background color of the element from transparent to black, but so far, my attempts have been unsuccessful. Can someone please pr ...

Bounding rectangle of a plane in Three.js according to the viewport and the problem of clipping near planes

This is a common issue with WebGL, but in order to provide clarity, I will be using three.js to illustrate the problem at hand. Imagine you have a plane and a perspective camera. Your goal is to determine the bounding rectangle of the plane relative to th ...

Trapping an iframe refresh event using jQuery

I am trying to dynamically load an iframe using jQuery. Here is my code: jQuery('<iframe id="myFrame" src="iframesrc.php"></iframe>').load(function(){ // do something when loaded }).prependTo("#myDiv"); Now, I need to capture th ...

Avoiding divs from crashing into each other

I've developed a game feature that allows users to chat. Each message is displayed as an absolute positioned element in the body with user x position set as the "left" CSS property. These messages are animated to move to the top of the screen. I want ...

Explore by the anchor tag

I've recently implemented a search bar utilizing Bootstrap. This is the code for the search bar: <div class="md-form mt-0"> <input class="form-control" id="myInput" type="text" placeholder="Sear ...

The `res.send()` function is showing [object object] and I am unable to access any properties

I've just started learning about REST APIs with express. I am encountering a strange issue where the code successfully console logs { name: 'Test', id: 1 } for the user, but when I send the response, it displays [Object object]. Additionally ...

Creating a JSON-based verification system for a login page

First time seeking help on a programming platform, still a beginner in the field. I'm attempting to create a basic bank login page using a JSON file that stores all usernames and passwords. I have written an if statement to check the JSON file for m ...

Is it possible to load multiple angular applications within a master angular shell application?

I am searching for a method to integrate multiple Angular applications into a single shell Angular application. The concept involves having different teams develop separate Angular apps that can be loaded within a main shell app visible to end users. Thi ...

Encountering an undefined property error while trying to access index '0' in Angular 6 with Angular Material's mat-radio-group component, specifically when attempting to set a dynamic variable within

Currently, I am working with Angular 6 and Angular Material. My project involves a dynamic list of polls with various options. I am attempting to display the selected option using two-way data binding. However, due to the dynamic nature of my list, I have ...

Efficiently sending VueJS data to a separate script

I am in the process of transitioning an existing site to VueJS, but I have encountered a roadblock when it comes to finding the best method to accomplish this task. The site currently utilizes D3-Funnel (https://github.com/jakezatecky/d3-funnel) to genera ...