What is the best way to exempt a unique situation from a directive's operation?

While troubleshooting a bug related to search functionality on my page, I encountered an issue with the search component. The search feature is working correctly and returning the expected values. However, when I clear the search criteria, I noticed that the first letter of the previous search term remains visible instead of disappearing.

After spending two hours reviewing the code, I identified the section of code causing the problem but am unsure how to resolve it.

The HTML for my component includes:

<mat-form-field appearance="standard">
      <input matInput
             pageSearch
             placeholder="{{'searchSettings'|translate}}">
    </mat-form-field>

The pageSearch directive is defined to trigger the valueChange method every time a key is released:

ngAfterViewInit() {
    const subscription = this.router.events
      .pipe(filter(e => e instanceof NavigationStart))
      .subscribe(event => {
          if (event) {
            this.pageSearchService.term.next('');
          }
        }
      );
    this.subscriptionsManager.add(subscription);
  }

@HostListener('keyup')
  valueChange() {
    this.pageSearchService.term.next(
      this.elementRef.nativeElement.value
    );
  }

The pageSearchService used by the directive is defined as follows:

@Injectable()
export class PageSearchService {
  term: BehaviorSubject<string>;
  searchableMatch: EventEmitter<any> = new EventEmitter<any>();

  constructor() {
    this.term = new BehaviorSubject('');
  }
}

I suspect that the problem lies in the directive always expecting a next() value and retaining the last value even when null. I attempted different approaches to address this issue without success:

  1. Adding a condition to check for empty string before calling BehaviorSubject
valueChange() {
    if (this.elementRef.nativeElement.value !== '') {
      this.pageSearchService.term.next(
        this.elementRef.nativeElement.value
      );
    }
  }

An alternative approach

valueChange() {
    if (this.elementRef.nativeElement.value !== '') {
      this.pageSearchService.term.next(
        this.elementRef.nativeElement.value
      );
    } else {
      this.pageSearchService.term.unsubscribe();
      this.pageSearchService.term._subscribe(this.elementRef.nativeElement.value);
    }
  }

However, both attempts resulted in errors. I'm currently at a loss on how to proceed and seek guidance on resolving the issue related to handling an empty string within the directive.

Additionally, there are other directives using the searchableMatch EventEmitter:

The SearchNoResultsDirective:

export class SearchNoResultsDirective implements AfterViewInit, OnDestroy {
  @Input('searchNoResults') sectionsId: string[];
  subscriptionsManager: Subscription = new Subscription();
  visibility: {
    term: string,
    visible: boolean
  } = {
    term: '',
    visible: true
  };

.
.
.

The SearchableSectionDirective:

export class SearchableSectionDirective extends BaseClass implements AfterViewInit {
  @Input('searchableSection') sectionId: string;

.
.
.

And the SearchableDirective:

export class SearchableDirective implements AfterViewInit, OnDestroy {
  @Input('searchable') sectionId: string;
  @Input() highlightColor = '#FFF176';
  match: EventEmitter<any> = new EventEmitter<any>();
  subscriptionsManager: Subscription = new Subscription();
  originalText: string;

  ngAfterViewInit() {
    this.originalText = this.elementRef.nativeElement.innerText;
    this.subscriptionsManager.add(
      this.pageSearchService.term.subscribe(term => this.checkIfMatch(term))
    );
  }

.
.
.

I am examining these directives to identify any potential issues that may be impacting the search functionality.

Answer №1

It seems like the issue lies within the placement of the logic in your function. I suggest adding the logic inside the checkIfMatch function only.

checkIfMatch(val: string) {

    let match = false;
    let clean = false;
    if (val) {

       // Insert logic here

     } else {
        // Make sure to include an else block in the function
        this.elementRef.nativeElement.innerHTML = this.originalText;

     }

}

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

Can you please explain how to upload an image and save it in the assets folder in Angular

Is there a way to upload an image in Angular and store it directly under the Assets folder, without the need for an API? ...

Using TypeScript and Angular to remove properties from an object

My RandomValue class and WeatherForecast class are causing me some trouble. The WeatherForecast class is functioning properly, populating the table with data as expected. However, the RandomValues class/interface appears to be returning a list of objects w ...

How can you add or remove an item from an array of objects in Angular/RXJS using Observables?

Purpose: The goal is to append a new object to an existing Observable array of objects and ensure that this change is visible on the DOM as the final step. NewObject.ts: export class NewObject { name: string; title: string; } Here's the example ...

Angular 5 is throwing an error that says: "There is a TypeError and it cannot read the property 'nativeElement' because it

Being aware that I may not be the first to inquire about this issue, I find myself working on an Angular 5 application where I need to programmatically open an accordion. Everything seems to function as expected in stackblitz, but unfortunately, I am enco ...

Utilizing the <slot> feature in Angular 5 for increased functionality

Currently, I am working on a single page application (SPA) where Vue framework has been utilized for development purposes. Front-End: Vue Back-End: NodeJs Within my application, there are other sub-modules built in Angular 4. I am looking to replicate th ...

The server is currently active on port 80, but unfortunately cannot be accessed using the domain

I've successfully configured my Angular5 server to run, but I'm facing an issue. When I start it on port 80, I am unable to access it using [domain].de or ; only seems to work. Why is this happening? To initiate the server, I use the following ...

Creating a conditional property in TypeScript based on an existing type - a comprehensive guide

Imagine if I had the following: type Link = { text: string; link: string; } interface BigLink extends Link { some: number; something: string; else: string; } However, there's a variable that shares all these properties except for the fact ...

latest version of PrimeNG dropdown is 16.2

I am inquiring about how to implement virtual scrolling in a dropdown menu and connect the virtual scroll with an API backend. Specifically, I would like to know how to trigger an API call when the user reaches the end of the scroll, incrementing the page ...

When trying to use `slug.current` in the link href(`/product/${slug.current}`), it seems to be undefined. However, when I try to log it to the console, it is displaying correctly

import React from 'react'; import Link from 'next/link'; import { urlFor } from '../lib/clients'; const Product = ({ product: { image, name, slug, price } }) => { return ( <div> <Link href={`/product/ ...

"Exploring the world of Typescript's return statements and the

I'm currently grappling with a design dilemma in typescript. Within my controller, I perform a validation process that can either return a 422 response, which ends the thread, or a validated data object that needs to be utilized further. Here's a ...

Received an error while using Mongoose 6 $group with Typescript stating that the property '_id' is not compatible with the index signature

Recently, I've been transitioning from JavaScript to TypeScript and also upgrading from mongoose 5.8 to version 6.1. The code snippet below used to work perfectly before: let getActionsTakenByApp = (store_url: string) => { return AppAction.aggr ...

Is there a compelling case for implementing Meteor in 2017?

Back in the day, Meteor was expected to revolutionize web development on node by simplifying the process of creating interactive applications. Though I'm not well-versed in its history, it seems like most of the development effort has shifted elsewher ...

Altering the appearance of a component that is currently selected and in use

Currently, I have incorporated a component with its selector within another component as shown below: <div class="col-xl-4" style="margin-bottom: 30px;"> <app-patient-info-accordion *ngIf="patient" [cardTitle]=&qu ...

How to properly handle Angular routing errors and best practices?

Currently, I have been delving into learning Angular to integrate with my Ruby on Rails application. However, I have encountered some challenges specifically related to routing. Here is a snippet from my app.routing file: import { NgModule } from '@ ...

Ensure the CSS class stays on Quill clipboard.dangerouslyPasteHTML

One of the challenges I face with using the Quill Text Editor is that when I use the method clipboard.dangerouslyPasteHTML to paste HTML into the editor, it does not maintain custom CSS classes. For example: let content= '<p class="perso-clas ...

What is the best way to hand off this object to the concatMap mapping function?

I'm currently in the process of developing a custom Angular2 module specifically designed for caching images. Within this module, I am utilizing a provider service that returns Observables of loaded resources - either synchronously if they are already ...

Jest encountered an error while attempting to parse the TypeScript configuration file

I've been working on setting up Jest with Babel and Typescript, following the guidelines provided here. However, when I run npm run test, I encounter the error message: Error: Jest: Failed to parse the TypeScript config file C:...jest.config.js` Th ...

Display the inputs from a reactive form in a different component

I am currently facing a situation where I have multiple components, such as component A, containing a reactive form. The data from these forms is stored in a central service. My goal now is to display a preview of this form in component B. However, upon na ...

execute npm scripts concurrently

Seeking a simpler solution for managing pre-script hooks in my package.json file. Currently, I have multiple commands that all require the same pre-script to run. While my current implementation works, I'm wondering if there is a more efficient way to ...

Strategies for retaining a list of chosen localStorage values in Angular6 even after a page refresh

When I choose an option from a list of localStorage data and then refresh the page, the selected data disappears. selectedColumns: any[] = []; this.listData = [ { field: "id", header: "Id", type: "number", value: "id", width: "100px" }, { field: "desc ...