Failing to initiate valueChanges when an input from the template is updated while mat-option is active

        
        <mat-form-field>
            <input matInput
                   [formControl]="affiliationName"
                   [matAutocomplete]="auto">
            <mat-label>Affiliation</mat-label>

            <mat-autocomplete #auto="matAutocomplete">
                <mat-option *ngFor="let item of items"
                            [value]="item.value"
                            (onSelectionChange)="onAffiliationSelect(item)">
                    <span class="semibold">{{item.code}}</span>
                </mat-option>
            </mat-autocomplete>
        </mat-form-field>

In the provided code snippet-

affiliationName: FormControl;


ngOnInit() {
    this.monitorInput();
}


monitorInput() {
    this.affiliationName
        .valueChanges.pipe(
        debounceTime(300),
        distinctUntilChanged(),takeUntil(this.affiliationDestroy))
            .subscribe(value => {
                  //do something
            });
    }

When a user inputs text in the field, I would like to trigger a search on the server side. However, after selecting an option from the list and populating the form control with the chosen value, I do not want the valueChanges to be activated again to prevent triggering another search. Is there a method to accomplish this without introducing an additional formControl or Boolean variable to manage the server call?

I came across a similar solution here, but my scenario necessitates having an input so using mat-select is not feasible for me. Angular 7 - not triggering "valueChanges" from the template (using mat-option)

Answer №1

Determine the type of emission originating from valueChanges. A string indicates user input, while an object suggests user selection.

To achieve this, ensure that the value of mat-option represents the entire object rather than just item.value. Additionally, for displaying the selected value in the input field, include a displayWith attribute in mat-autocomplete. This attribute takes a function as an argument which receives the mat-option value of the selected option and returns a string to display in the input control.

<mat-form-field>
  <input matInput
         [formControl]="affiliationName"
         [matAutocomplete]="auto">
  <mat-label>Affiliation</mat-label>
</mat-form-field>

<mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn()">
  <mat-option *ngFor="let item of items"
              [value]="item"
              (onSelectionChange)="onAffiliationSelect(item)">
    <span class="semibold">{{item.code}}</span>
  </mat-option>
</mat-autocomplete>
affiliationName: FormControl = new FormControl();

ngOnInit() {
  this.listenToInput();
}

displayFn(): (item: any) => string {
  return (item: any): string => item && item.value ? item.value : '';
}

listenToInput() {
  this.affiliationName 
    .valueChanges.pipe(
      filter((v: any) => typeof v === 'string'),
      debounceTime(300),
      distinctUntilChanged(),
      takeUntil(this.affiliationDestroy)
    ).subscribe(value => {
      //do something
    });
}

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

Filtering with Angular to eliminate items based on their unique identifiers

What is the best way to filter values in Angular or remove values based on their IDs? I need to delete data or objects from an array of objects where the ID is 5, 12, and 9. In addition, we want to filter using multiple IDs, such as when the ID is 5, 12, ...

How to define type definitions specifically for the window scope in VSCode

I'm in the process of creating TypeScript type definitions for a library that is developed with webpack and is designed to be loaded into the global window object. This library is specifically made for easy integration into the browser using a CDN. A ...

Encountering an issue that states that jQuery must be included before Bootstrap's JavaScript is causing an

I encountered the following exception: bootstrap.js:240 Uncaught TypeError: Bootstrap's JavaScript requires jQuery. Make sure to include jQuery before Bootstrap's JavaScript at Object.jQueryDetection (bootstrap.js:240) at bootstrap.js:255 a ...

Generating JavaScript files automatically upon initiating the npm start command

As I develop an Angular2 app with typescript, I encounter a situation where running npm start results in all .ts files being compiled into javascript files and saved in the directory. Is there a way to disable this automatic compilation? The contents of m ...

The union type cannot function effectively in a closed-off environment

Here is the code snippet I am working with: if (event.hasOwnProperty('body')) { Context.request = JSON.parse(event.body) as T; } else { Context.request = event; } The variable event is defined as follows: private static event: aws.IGateway ...

Angular-cli allows importing custom classes just like importing Angular classes

I believe this question may have come up previously, but I'm not sure where to look for it. Please point me in the right direction if this is a duplicate. Within my angular-cli application, I've noticed that I can easily import classes from the ...

What is the nature of the Error in React Query and what strategies can be employed to manage various scenarios?

In my project, I am using React Query with TypeScript to retrieve data. I am attempting to utilize the error returned by the useQuery hook to show a descriptive message if an error exists like this: {isError && (error)? <p className=" text-[#ff0000 ...

The state is accurate despite receiving null as the return value

I'm feeling a bit lost here. I have a main component that is subscribing to and fetching data (I'm using the redux dev tools to monitor it and it's updating the state as needed). In component A, I am doing: public FDC$ = this.store.pipe(sel ...

Transfer an Array of Objects containing images to a POST API using Angular

Looking to send an array of objects (including images) to a POST API using Angular and Express on the backend. Here's the array of objects I have: [{uid: "", image: File, description: "store", price: "800"} {uid: "f ...

Creating a personalized aggregation function in a MySQL query

Presenting the data in tabular format: id | module_id | rating 1 | 421 | 3 2 | 421 | 5 3. | 5321 | 4 4 | 5321 | 5 5 | 5321 | 4 6 | 641 | 2 7 | ...

Comparing time in Angular using Typescript

I have an Angular application where I need to constantly monitor the current time and check if it is past 3 PM. To achieve this, I am using Date.now() to retrieve the current time and updating it every minute in the constructor as shown below: setInterva ...

Transforming a discriminated union into an object

Looking for a solution to transform a discriminated union similar to this: type Something = { type: 'mode'; values: 'first' | 'second'; } | { type: 'part'; values: 'upper' | 'lower'; ...

I'm looking for the best place to place code for initialization before initializing a custom module in Angular 14

Using ngrx/data 14 and Angular 14, I have constructed a unique custom module that I include in my app.module.ts file as follows: @NgModule({ declarations: [ AppComponent ], imports: [ ... AppRoutingModule, MyCustomModule, ... ] ...

What is the process for obtaining data from an observable using a parameter, and subsequently updating that data?

I am dealing with a collection in my Firestore database called 'user' which contains documents with specific attributes. users:{ userId:string; userName:string; stars:number } My goal is to retrieve the star rating of a particu ...

How to customize the default color palette in Bootstrap 5 for a Next.js project using Sass?

After successfully loading and implementing Bootstrap in my next.js app, I have been struggling for several days to customize the default color scheme. In my global.scss file: @import "../node_modules/bootstrap/scss/bootstrap"; $primary:#f3ced6 ...

Using WebdriverIO with Angular to create end-to-end tests in TypeScript that involve importing classes leads to an error stating "Cannot use import statement outside a module."

I am facing an issue while trying to set up a suite of end-to-end tests using wdio. Some of the tests utilize utility classes written in TypeScript. During the compilation of the test, I encountered the following error: Spec file(s): D:\TEMP\xx& ...

Creating an HTTP gateway with Observables

When dealing with multiple requests, I need to pause them until the authentication of the http request has been confirmed. Essentially, I require an http gate where some requests can pass without authentication, while others need to wait for the token to b ...

An issue was encountered in Angular where a TypeError occurred, stating that a function is not recognized when attempting to invoke a

When attempting to call a method of an object.object[].method in Angular 4, I encountered the following error: Error Message: OrderComponent.html:30 ERROR TypeError: item.increaseQuantity is not a function at OrderComponent.increaseQuantity (order ...

Adding a separator for thousands on data labels in ng2-charts

Take a look at this demonstration: http://embed.plnkr.co/7fGsiuRjcF0M0Ffeoml2/ If I modify the data to be: data: [2000, 3000, 4000, 8000, 12000, 12850] Can I add thousand separators to the dataset label? For example: 5,000 10,000 15,000 ...

Integrate the use of `Refresh Token` into an `Angular` application

In my current project, I am tackling the integration of Spring Security with OAuth2 and JWT: The author suggests that I can access resources using a token in the following manner: To access a resource, use the following command (assuming you have config ...