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

Angular2 material dropdown menu

Currently, I am studying angular2 with its material design. One of the modules I am using is md-select for material and here is a snippet of my code: <md-select> <md-option value="1">1</md-option> <md-option value="2">2< ...

Transferring Information Between Components

After logging into my login component, I want to pass data to my navbar component but unfortunately, my navbar content does not update. The navbar component is located in the app-module while the login component is in a separate module. I attempted to us ...

What is the process for generating flexible paths (URL strings) in angular applications?

Within my <app-parent> component, I have multiple buttons that each open a new floating panel on top of the parent. These floating panels also contain buttons that trigger the opening of additional floating panels, creating a stacking effect. My go ...

Managing CORS in Angular2 for REST WebApi calls

Currently, I am utilizing an Angular 2 front end along with a WebApi backend where the WebApi is CORS enabled. var cors = new EnableCorsAttribute("*", "*", "*"); GlobalConfiguration.Configuration.EnableCors(cors); This setup works well with different sit ...

Modifying an element's property by using the unsubscribe function

I am currently in the process of developing a new Angular 4 application. The app is connected to a restful web service, which is used to retrieve data from the database. To handle this functionality, I have created a front end service named UsersListServi ...

Sign up for the completion event within the datetime picker feature in Ionic 2

How can I subscribe to the "done" event in Ionic2, where I want to trigger a function after selecting a date? <ion-icon class="moreicon" name="funnel"> <ion-datetime type="button" [(ngModel)]="myDate" (click)="getData()"></ion-datetime> ...

Ways to apply the strategy pattern in Vue component implementation

Here's the scenario: I possess a Cat, Dog, and Horse, all of which abide by the Animal interface. Compact components exist for each one - DogComponent, CatComponent, and HorseComponent. Query: How can I develop an AnimalComponent that is capable of ...

Tips for typing a narrow JSX.Element

Is there a way to create a variable in React that can be either a component or a string? Like this: function MyComponent(): JSX.Element { let icon: JSX.Element | string = "/example.png"; return <div>{typeof icon === "JSX.Element" ? icon : <i ...

The loading of woff2, woff, and ttf files resulted in a 400 error

Can you explain why the woff2, woff, and ttf files in the "assets" folder are not loading? Any suggestions on how to fix this issue? ...

Messages are not being emitted from the socket

I've been encountering an issue with message transmission from client to server while using React and ExpressJS. When I trigger the sendMessage function on the client side, my intention is to send a message to the server. However, for some reason, the ...

Is array.length access cached by NodeJS?

Lately, I've been pondering whether accessing the array.length getter is cached by NodeJS. I've searched for conclusive answers about JS interpretation in browsers, but since I am working on apps in Typescript, that information does not directly ...

Enhancing Code Completion Feature for Multiline Strings in Visual Studio Code

When attempting to include HTML code in a multiline string using backticks within TypeScript, I've noticed that VS Code doesn't offer auto-completion for the HTML tags. Take this example: @Component({ selector: 'app-property-binding&ap ...

Issue encountered while attempting to utilize a basic redux reducer to define a boolean value, regarding a mismatch in overrides

Currently, I am working on a project to enhance my understanding of Redux and Typescript. I am still navigating through the learning curve in this area. Based on what I have learned from a book, I have established a "slice" that includes definitions for r ...

Cache for JSON Schema in VS Code

After updating to TypeScript 1.5 (now out of beta), I am eager to utilize the json schema helpers in VS Code. Upon configuring tsconfig.json, I noticed that only commonjs and amd module options are available, while umd and system are missing based on this ...

The slides in Swiperjs are having trouble moving smoothly

I am experiencing some challenges with swiperjs where the slides are not snapping to the next slide and I am unable to fetch the active index from them. Below is a snippet of my code where I am using typescript, swiperjs version 6.84, and the Ionic frame ...

Reasons behind Angular HttpClient sorting JSON fields

Recently, I encountered a small issue with HttpClient when trying to retrieve data from my API: constructor(private http: HttpClient) {} ngOnInit(): void { this.http.get("http://localhost:8080/api/test/test?status=None").subscribe((data)=> ...

Error encountered while attempting to obtain OAuth2 API authorization token in ExpressJS Node.js Angular: "getaddrinfo ENOTFOUND"

Recently, I developed an angular application that sends an HTTP post request to a Node/Express.js endpoint upon clicking a button in order to obtain an authorisation token. I successfully configured the necessary credentials for basic OAuth2 authorisation ...

Utilizing NPM Workspace Project in conjunction with Vite to eliminate the necessity of the dist folder during the Vite build process

I am currently working on a project that involves a module using full path exports instead of index files. This project is divided into 2 NPM workspaces: one called core and the other called examples. The challenge I am facing is avoiding long import pat ...

pick only one option from each row

I am working on a feature where I have five rows with two checkboxes each generated using a loop and property binding. Currently, clicking on one checkbox selects all elements in the column. However, I want to achieve selection row-wise. Is there a method ...

The subscription function in observables may result in values that are undefined

I integrated a new angular 2 library into my application called "angular2-grid". This library is located within the node_modules folder. Furthermore, I created a service as shown below: import { Injectable } from '@angular/core'; import { Htt ...