Tips for resolving the issue with the 'search input field in the header' across all pages in angular 5 with typescript

I currently have a search field in the header that retrieves a list of records when you type a search term and click on one of them. The search function utilizes debounceTime to reduce API requests, but I'm encountering an issue where the search doesn't work on the overview page. How can I fix this and make the search function properly on the overview page?

Below is the code for the search input field:

<input #searchText [(ngModel)]="searchFilterText" id="m_quicksearch_input_disabled" autocomplete="off" type="text" name="searchFilterText" class="m-list-search__form-input" value="" placeholder="Search...">

The search function in the header component after debounceTime processing is as follows:

processSearchTerm() {
    if (this.searchTextRef) {
        fromEvent(this.searchTextRef.nativeElement, 'keyup')
            .pipe(
                debounceTime(AppConsts.DEBOUNCE_TIME), 
                distinctUntilChanged()
        ).subscribe(
            value => this.getMyData(this.searchTextRef.nativeElement.value.trim())
            );
    }
}

This is the code fetching search results in the header component:

getMyData(searchTerm: string): void {
    if (searchTerm) {
        this.initSpinner = true;

        this._myDataServiceProxy.getmyDatasorSearchResults(
            searchTerm
        ).subscribe(result => {
            this.myDataRecords = result.items;
            this.myDataRecordTotal = result.totalCount;

            this.initSpinner = false;
        });
    } else {
        this.myDataRecordTotal = AppConsts.RESET_MYDATA_RECORD_COUNT;
    }
}    

Code snippet to view detailed information about the data in the header component:

goToMyDataOverview(id: number): void {
    if (id) {
        this._router.navigate([`/app/main/data/${id}`]);
    }
}

Anchoring the list items in the header component with an anchor tag:

<a (click)="goToMyDataOverview(item.id)"
   href="javascript:;"
   class="m-list-search__result-item"
   *ngFor="let item of myDataRecords; let i = index;">
    <span class="m-list-search__result-item-pic"><img class="m--img-rounded" src="assets/common/images/default-profile-picture.png" title="" alt="Profile picture"></span>
    <span class="m-list-search__result-item-text">{{item.firstname}} {{item.lastname}}</span>
</a>    

Here's the code for the overview component:

ngOnInit(): void {
    const id = this.route.snapshot.paramMap.get('id');
    if (id) {
        this.getData(id); 
    }
}

getData(id: string): any {
    if (id) {
        this.initSpinner = true;
        this._dataServiceProxy.getDataInformationById(
            id
        ).subscribe(result => {
            this.myData = result.data;
        });
    }
}

Answer №1

There is a substantial amount of code provided below, so let's start by breaking it down:

If we consider the Template section:

<input #searchText 
       [(ngModel)]="searchFilterText" 
       id="m_quicksearch_input_disabled" 
       autocomplete="off" 
       type="text" name="searchFilterText" 
       class="m-list-search__form-input" 
       value="" placeholder="Search...">

And then move on to the associated component:

processSearchTerm() {
    if (this.searchTextRef) {
        fromEvent(this.searchTextRef.nativeElement, 'keyup')
            .pipe(
                debounceTime(AppConsts.DEBOUNCE_TIME), 
                distinctUntilChanged()
        ).subscribe(
            value => this.getMyData(this.searchTextRef.nativeElement.value.trim())
            );
    }
}

We can simplify accessing the bound property searchFilterText instead of using

this.searchTextRef.nativeElement.value
, avoiding potential issues.

An improved solution is to utilize reactive forms for better functionality with debounceTime:

Template:

<input [formControl]="searchTerm" 
       id="m_quicksearch_input_disabled" 
       autocomplete="off" 
       type="text" name="searchFilterText" 
       class="m-list-search__form-input" 
       value="" placeholder="Search...">

Observe the binding to formControl, a directive within reactive forms.

Component:

searchTerm = new FormControl();

this.searchTerm.valueChanges
  .pipe(
    debounceTime(AppConsts.DEBOUNCE_TIME),
    distinctUntilChanged()
  ).subscribe(
    value => this.getMyData(value.trim())
  )

This approach makes use of reactive forms' built-in valueChanges observable for tracking changes.

Regarding the handling of data filtering and display, there seems to be segregation between the header component and detail page in the current structure.

To extend the search functionality across all pages, you have several options:

1) Develop the search UI as a standalone component that can be embedded on any page using tags like

<searchForm></searchForm>
. This allows communication via @ViewChild.

2) Organize pages with the search UI at the top and content underneath as shown below:

<searchForm></searchForm>
<router-outlet></router-outlet>

You can employ a service to share the searchTerm among components efficiently.

For a basic demonstration of the latter option, refer to this example: https://stackblitz.com/edit/angular-simpleservice2-deborahk

The provided sample incorporates a search component, tabs for different pages, and utilizes a service to facilitate searchTerm sharing throughout.

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

What is the process for importing an mp3 file into a TypeScript project?

I'm currently working on a web application using React and TypeScript. My current challenge involves importing an mp3 file for use with the use-sound library, but I keep encountering this error in TypeScript: "Cannot find module '../../as ...

The element 'mat-form-field' is unrecognized: 1. Confirm if 'mat-form-field' is an Angular component and ensure it is included in this module

I've been struggling to configure Angular material components in my project. Whenever I try to use mat-input, I encounter errors even after importing all the necessary dependencies. Here is a snippet of the code within my component: <form class="e ...

Utilizing Typescript: Ensuring an array includes only specified values from an enum through strict enforcement

In my Angular application, I have an HTTP service that returns the allowed accesses for a specific user. The response structure is as shown below:- { "accessId": 4209318492034, "folderPath": "data/sample_folder/", ...

Is it possible to eliminate the port number in Angular 7?

Currently, I am utilizing Angular in conjunction with an ASP.Net Web application. One interesting observation I've made is that when I use ng build, the app builds and runs on a URL without any port number. However, if I run the app using ng serve, it ...

Instantiate a TypeScript object and establish its type by setting restrictions derived from an input object

I have been working on creating a function that takes an object A: { [key: string]: string | undefined } as its parameter. The goal is to generate a new object B with all properties from A, converting each string property to type number, and each string | ...

Combining various POST requests by matching the common value in each array. (Angular)

Here are the two different sets of data: "statusCode": 200, "data": [ { "color": { "id": "1111", "name": null, "hex&quo ...

Utilizing TypeScript/React to Access Data from an Excel Spreadsheet

Hey there! I've been working on a Single-Page-Application with Typescript and React, and now I need to read data from an Excel sheet. The xlsx Library (npm) seems to be the way to go, but I'm having trouble getting it to work. Can anyone offer an ...

Is the return type of 'void' being overlooked in TypeScript - a solution to avoid unresolved promises?

When working in TypeScript 3.9.7, the compiler is not concerned with the following code: const someFn: () => void = () => 123; After stumbling upon this answer, it became apparent that this behavior is intentional. The rationale behind it makes sens ...

Having trouble accessing the database in Angular and Ionic through a provider on a Tabbed page

I created a Home page with tabs using Ionic 3 and Angular. The tabs are named Stats and Calc. When clicking on the Stats tab, it triggers the class/component stats.ts (displayed below). This component utilizes two providers: CropProvider and ContractProvi ...

Error: No provider found for _HttpClient in the NullInjector context

Hello everyone, I am new to Angular and currently facing an issue that has me stuck. The error message I'm receiving is as follows: ERROR NullInjectorError: R3InjectorError(Standalone[_AppComponent])[_ApiCallServiceService -> _ApiCallServiceService ...

Issue encountered during the creation of a new Angular application (npm ERROR! 404 Not Found: @angular/animations@~7.1.0.)

I am currently using Windows 10, Node v11.0.0, and Angular CLI: 7.1.4. I encountered an error when trying to create a new Angular application. The error message is npm ERR! code E404 npm ERR! 404 Not Found: @angular/animations@~7.1.0. Error stack: 0 info ...

Executing various tasks concurrently with web workers in Node.js

Looking to read multiple JSON files simultaneously and consolidate the data into a single array for processing on a Node.js server. Interested in running these file readings and processing tasks concurrently using web workers. Despite finding informative ...

Building a ng-select in reactive forms involves adding dynamic options to a select box using Angular

I've been scouring various websites, but I haven't had any luck finding a solution. How can we create an ng-select in reactive forms? I want to include the following HTML tag within a reactive form, as shown in the code snippet below. HTML: < ...

What is the best way to effectively use combinedLatestWith?

https://stackblitz.com/edit/angular-ivy-s2ujmr?file=src/app/country-card/country-card.component.html I am currently working on implementing a search bar in Angular that filters the "countries$" Observable based on user input. My approach involves creatin ...

Can you explain the distinction between @types/material-ui and the official @mui/types bundle?

When it comes to npm packages, I came across @types/material-ui and @mui/types. I'm aware that the former is backed by the Definitely Typed community, but what's the reasoning behind its existence when an official types package already exists? D ...

Discovering the IMEI number with Ionic4 and Angular

Recently, I started working with the Ionic framework and I'm trying to find a way to uniquely identify each device. My initial thought was to obtain the IMEI number, but I'm unsure of how to do that. I attempted to use Ionic4 with Angular cordova ...

Exploring the concept of type inheritance in TypeScript

I am working on developing various components for an app, each with its own specific structure. The general structure is defined as COMPONENT. Within this framework, there are two distinct components: HEADING and TEXT. These components should be subclasses ...

Having trouble assigning the class property in Angular 5

Upon loading the page, a list of products is retrieved from an external JSON source. Each product in the list has a corresponding BUY button displayed alongside it, with the ID of the respective product assigned to the button. The intention is that when a ...

Every time I implement *ngSwitch in a Bootstrap navbar, the visual styling unexpectedly vanishes

<ul class='nav navbar-nav'> <li class='nav-item'> <ul [ngSwitch]='isLoggedIn' class='nav-item'> <li *ngSwitchCase=true> ...

Broken Encoding Issue with Server-Side HttpClient Response in Angular 5 Universal

I have encountered an issue with Angular 5 Universal and server side rendering (ssr). When I make a GET request using HttpClient on the server side, the response seems to have encoding problems. However, the same code works perfectly fine on the client sid ...