Angular – How to close/remove search input when input empty, click outside input element or press esc

Published

I have a search bar that displays results when fed with text input, the problem is:

  1. the search results do not go away even if the input field/search bar is empty.
  2. It does not close if I press ESC or click outside the search bar or search results. I have tried different things with renderer and host view, I can’t make it work. If it was regular js, I’m sure I would have been to solve this. Angular just has too many special quirks, I need some help with this.

this is what the problem looks like: problem

components.ts file (removed my failed attempts):

import {
  Component,
  OnInit,
  Renderer2,
  ElementRef,
  ViewChild,
} from '@angular/core';

import { faSearch } from '@fortawesome/free-solid-svg-icons';
import { CountryService } from '../services/country.service';
import { OneCountry } from '../country';

@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.css'],
})
export class SearchComponent implements OnInit {
  faSearch = faSearch;
  countries: OneCountry[] = [];
  searchTerm: any;
  cachedCountries: OneCountry[] = [];
  

  constructor(private countryService: CountryService) {}

  ngOnInit(): void {}

  onKeyPressEvent(event: KeyboardEvent): void {
    this.getCountries();
  }

  getCountries(): void {
    this.countryService.searchCountries().subscribe({
      next: (countries) => (
        (this.countries = countries),
        (this.cachedCountries = this.countries),
        console.log(this.countries)
      ),
    });
  }

  search(value: string): void {
    this.countries = this.cachedCountries.filter((val) =>
      val.name.toLowerCase().includes(value)
    );
  }
}

This is the template file:

<div id="search-component" class="w-full md:w-[32rem] dark:bg-darkblue-100">
  <div
    class="w-full px-4 h-[53px] flex justify-around align-center shadow-md border rounded"
  >
    <figure class="w-1/6 grid place-items-center">
      <fa-icon
        class="text-darkblue-100 dark:text-white text-lg"
        [icon]="faSearch"
      ></fa-icon>
    </figure>

    <input
      class="w-5/6 h-full focus:outline-none dark:bg-darkblue-100"
      placeholder="Search for a country..."
      #searchBox
      name="searchTerm"
      id="search-box"
      (input)="search(searchBox.value)"
      [(ngModel)]="searchTerm"
      (keypress)="onKeyPressEvent($event)"
    />
  </div>

  <ul class="mt-0 pl-0 relative z-20">
    <li
      class="z-20"
      *ngFor="let country of countries | searchFilter: searchTerm; index as i"
    >
      <a
        *ngIf="i < 10"
        routerLink="/detail/{{ country.name }}"
        class="z-20 border border-t-0 inline-block w-full md:w-[32rem] p-4 rounded shadow hover:bg-darkblue-100 hover:text-white dark:hover:bg-white dark:hover:text-black h-12 box-border"
        >{{ country.name }}</a
      >
    </li>
  </ul>
</div>

Source: Angular Questions

Published
Categorized as angular, dom, html, javascript, typescript Tagged , , , ,

Answers

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Still Have Questions?


Our dedicated development team is here for you!

We can help you find answers to your question for as low as 5$.

Contact Us
faq