Unable to retrieve the updated value from the service variable

I'm attempting to implement a filter that allows me to search for items based on a service variable that is updated with user input. However, I am only able to retrieve the initial value from the service in my component.

Service HTML (whatever is typed in is correctly assigned to the variable searchInput):

<input [value]="searchInput" (keyup)="searchInputChange.next(searchFilterService.applyFilter($event.target.value))">

Service TS (named 'component' since there is already a service with the same name currently):

export class SearchFilterComponent {

    searchInput: string = 'test';
    searchInputChange: Subject<string> = new Subject<string>();

    constructor(
        public searchFilterService: SharedSearchFilterService) {
        this.searchInputChange.subscribe((value) => {
            this.searchInput = value
        });
    }

    getSearchInput(): string {
        return this.searchInput;
    }
}

Filter Service TS:

@Injectable()
export class SharedSearchFilterService {
    
    applyFilter(filterValue: string) {

        if (filterValue) return filterValue;
        else return ''; // To prevent receiving 'undefined'
    }
}

Component HTML (initially fetching the value 'test', but not updating with new values from the service):

<ng-container *ngIf="searchFilterService.licenceFilter(item, service.getSearchInput())">

Example link: https://stackblitz.com/edit/angular-buagfs

Answer №1

The code snippet provided shows the usage of the AppService component in an Angular application. The component includes a search functionality that emits values using the @Output decorator.

app.service.ts

@Component({
  selector: 'search-component',
  template: `
    <div fxLayout="row" fxLayoutAlign="space-between center">
      <input
        [(ngModel)]="searchInput"
        (keyup)="onKeyUp()"
      />
    </div>
  `
})
export class AppService implements OnInit {
  searchInput: string = 'test';
  @Output() inputValue = new EventEmitter<string>();

  constructor() {
  }

  ngOnInit() {
    this.inputValue.emit(this.searchInput);
  }

  onKeyUp(): void {
    this.inputValue.emit(this.searchInput);
  }

  getSearchInput(): string {
    return this.searchInput;
  }
}

app.component.html

<hello name="{{ name }}"></hello>
<search-component (inputValue)="onInputValueEmitted($event)"></search-component>
<div *ngIf="searchInput == 'test'">This shouldn't be seen if value is not 'test'</div>

app.component.ts

import { Component, OnInit } from '@angular/core';
import { AppService } from './app.service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name = 'Angular';
  searchInput = '';

  constructor(private service: AppService) {}

  onInputValueEmitted(value: string) {
    this.searchInput = value;
  }
}

You can view the Stackblitz sample here

Answer №2

To ensure the variable this.searchInput is equal to the value passed to the function getSearchInput, you must assign the value like so:

//make sure to pass an argument to the function
getSearchInput(searchInput:string): string {
    this.searchInput=searchInput //<--assigning the variable
    return this.searchInput;
  }

Additionally, Angular offers another method to achieve the same result: using FormControl along with the valueChanges property.

If you are using a FormControl in your .html file:

<input [formControl]="control" />

In your .ts file:

//create a "getter" for easy access to this.control.value
get searchInput()
{
  return this.control.value
}
set searchInput(value)
{
   this.control.setValue(value)
}

control=new FormControl()
constructor() {
  this.control.valueChanges.subscribe(value => {
      console.log('Testing subject: ', value);
  });
}

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 most efficient method of incorporating a navbar into an Angular project?

What is the most effective way to display a navbar in my Angular application? Currently, I have placed my nav-bar component at the top of my app.component.html file and am using a service to determine which items in the navbar should be visible. This is ...

Convert an HTML file to .msg format or prevent the send button from functioning in Outlook messages

I am trying to figure out how to save an HTML file as a .msg format in order to send it later. The HTML is basically a mock of a regular email with just the basic features like from, to, cc, subject, and body. I'm not quite sure how to go about achiev ...

What is a suitable alternative to forkJoin for executing parallel requests that can still complete even if one of them fails?

Is there a more robust method than forkJoin to run multiple requests in parallel and handle failed subscriptions without cancelling the rest? I need a solution that allows all requests to complete even if one fails. Here's a scenario: const posts = th ...

The element 'nz-list-item-meta-title' in NG-ZORRO is unrecognized

After installing NG-ZORRO for my project, I decided to start by incorporating their list component. However, I encountered errors with elements such as: 'nz-list-item-meta-title' and 'nz-list-item-action' not being recognized. I have e ...

Invisible Angular Material Date Picker Issue

I am facing an issue with the angular material datepicker in my project. The datepicker itself remains invisible, but it functions when I click on its location or where the calendar icon is placed. To make it more clear for users, I have added a button nex ...

SlidingPane header in React disappearing behind Nav bar

Here is the code snippet from my App.js file: export class App extends React.Component { render() { return ( <BrowserRouter> <NavigationBar /> <Routes /> </BrowserRout ...

Having trouble with Updating the Records in NodeJs and Angular

As a beginner in Node.js with Angular, I have been working on a simple CRUD application. Adding, deleting, and viewing records works fine for me. However, I am facing issues with updating records. Whenever I make changes on the form and click the submit bu ...

Is there a way to exclusively view references of a method override in a JS/TS derived class without any mentions of the base class method or other overrides in VS Code?

As I work in VS Code with TypeScript files, I am faced with a challenge regarding a base class and its derived classes. The base class contains a method called create(), which is overridden in one specific derived class. I need to identify all references ...

Invoke a function within the embedded element

I currently have two components, known as app-student-list and app-student-detail. My goal is to incorporate the student-detail within the student-list in the following manner: Within app-student-detail.html: <p>Student Detail Component content go ...

The TypeScript error "File 'XXX' is not recognized as a module" is preventing successful compilation

Is there a way to import a module from an external file into another TS file? Even after following the steps, when I tried to do so in VSCode, it gave me an error saying that the file 'XXX' is not a module: Here's the error I encountered I ...

Creating dynamic attributes for hibernate mapping through front-end integration

Currently, I am facing the challenge of inserting JSON data into our database using a combination of Spring Boot, Hibernate, and Angular. The specific attribute name within this JSON data remains unknown during compile time. Is there a viable solution tha ...

Strange behavior observed in Angular Reactive form

I've been troubleshooting this code snippet: login.component.html <div class="main"> <div class="image"> <img src="./assets/icons/login.png" alt="Login"> <p>Sign in t ...

The data type 'boolean' cannot be assigned to the type 'StoryFnReactReturnType' in a React Storybook project using Typescript

I am currently working on setting up a Button component with Storybook in typescript. I am referencing The Documentation and using this specific example. Below is my Component and its story: components/Button.tsx: import {FC} from 'react'; exp ...

Ways to conceal an element in Angular based on the truth of one of two conditions

Is there a way to hide an element in Angular if a specific condition is true? I attempted using *ngIf="productID == category.Lane || productID == category.Val", but it did not work as expected. <label>ProductID</label> <ng-select ...

Can you set up a mechanism to receive notifications for changes in an array variable in Angular?

I'm exploring methods to delay an HTTP request until the user stops interacting. I am considering using the debounceTime() operator from RxJs, but I need this to be triggered by changes in an array that I have defined. Here is the scenario: export c ...

Setting a timeout from the frontend in the AWS apigClient can be accomplished by adjusting the

I am currently integrating the Amazon API Client Gateway into my project and I have successfully set up all the necessary requests and responses. Now, I am trying to implement a timeout feature by adding the following code snippet: apigClient.me ...

Encountering issue in Angular 14: Unable to assign type 'Date | undefined' to type 'string | number | Date' parameter

I have been working on an Angular 14 project where I am implementing a Search Filter Pipe. Below is the code snippet I am using: import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'transferFilter' }) export class Trans ...

Utilizing a React hook to render and map elements in a function

Can the hook return function be assigned to a render map in React? In this example, we have the socialAuthMethodsMap map with the onClick parameter. I tried to assign the signInWithApple function from the useFirebaseAuth hook, but it violates React's ...

Tips for resolving the issue of 'defineExpose' method being undefined in Vue3

Struggling to pass a method from child to parent; unfortunately, the defineExpose() method seems to be malfunctioning. Could anyone provide guidance on what might be going wrong? For additional context, feel free to check out my previous question <scri ...

Using the ternary operator for rendering components in TSX: A beginner's guide

Currently, I am retrieving data from a server. The component to display is determined based on the result of this retrieval process. const response = fetch(url) .then((result) => result.json()) .then((data) => data) .catch((e) => { ...