Learn how to update scope variables in Angular.io's mat-autocomplete using the [displayWith] function feature

I'm encountering a problem where I am unable to update locally declared variables in the component controller that triggers the mat-autocomplete. The issue is that these variables are confined within a specific scope, preventing me from making any modifications.

Does anyone have suggestions or insights on how to update the mat-autocomplete's scope variables?

Basically, I am trying to combine a display string with a variable linked to the input model. This configuration generates an autocomplete input field that provides user-friendly guidance. However, the text does not get updated promptly when clearing the input, as it keeps adding unnecessary content continuously.

html

  <input
   [(ngModel)]="filter>

  mat-autocomplete
    #auto="matAutocomplete" 
    [displayWith]="displayFn">
    <mat-option
      *ngFor="let option of filteredOptions | async"
      [value]="option">
      {{ option }}
    </mat-option>
  </mat-autocomplete>

component.ts

  displayFn(search): string | undefined {
    if(!search) return; //check if the search isn't already populated
    if(!search.match(/(=|\*)/)){
      if(this.filter){
        this.filter += ' ' + search + '==*term*';
      }else{
        this.filter = search +'==*term*';

      }
      return this.filter; //this isn't persisting across the lifecycle
    }
  }

Answer №1

You are faced with a choice between two options here. The first option involves using

[displayWith]="displayFn.bind(this)"
, which may seem strange in the Angular realm but rest assured it does work (although I did encounter an Error in WebStorm mentioning ng: Unknown Method bind). Alternatively, you can opt for the second option which entails utilizing an arrow function to maintain the context effectively.

displayFn(offer?: Offer): string | undefined {
    return offer && offer.name == this.currentOffer.name ? offer.name : undefined;
}

displayFnWrapper() {
   return (offer) => this.displayFn(offer);
}

Incorporating this into your template would look like:

<mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFnWrapper()" (optionSelected)='assign($event.option.value)'>
    <mat-option *ngFor="let offer of filteredOffers$ | async" [value]="offer">{{ offer.name }}</mat-option>
</mat-autocomplete>

Answer №2

Let's take MyClass as an example, where

@Input() modeCity = false;

Upon initializing, I can access and manipulate the modeCity within ngOnInit(), which reflects across various methods in the class.

In the HTML section,

<mat-autocomplete #auto="matAutocomplete" autoActiveFirstOption [displayWith]="itemDisplayFn" (optionSelected)="selected($event)">

However, when it comes to the method itemDisplayFn(item: ..) in the corresponding TypeScript file, the modeCity appears to be undefined.

After some investigation, I discovered that the method itemDisplayFn() seems to have a static context. As a solution, I introduced a new property:

static staticModeCity = false;

This staticModeCity can be configured within the ngOnInit() function like this:

MyClass.staticModeCity = true

Subsequently, it can be utilized within the Method itemDisplayFn() as follows:

if(MyClass.staticModeCity) ....

The reason for this behavior remains unclear to me at this point. It is essential to note that static properties might lead to conflicts if the same component is instantiated multiple times within a parent component.

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

Ways to address issues in my tree-building algorithm when the parent ID is missing

Currently, I'm in the process of creating a function to build a tree. Everything seems to be functioning correctly until I encounter a scenario where a document is added with a parentID that doesn't exist in the list. The root node is intended to ...

You should be providing a string value as expected. It seems that you may have overlooked exporting your component from the correct file it was defined in, or perhaps there is confusion with default and named

I encountered a strange error despite meticulously organizing and exporting/importing files. The code is structured from components to the App render method. Item.js import React from 'react'; import './Global.css' const Item = ({data ...

Deduce the property type by the existence of the value

Here's a situation I'm trying to address in a simple way: if the entity prop is present, I want the onClick callback to receive the entity string, otherwise it should receive nothing. type SnakeOrCamelDomains = "light" | "switch" | "input_boolean ...

Using AngularJS to invoke the ng-required directive and trigger a function

Is it possible to make the required value dependent on a function? Something similar to this? I need to achieve this in order to dynamically change the required attribute for form inputs... HTML: Name: <input type="text" ng-model="user.name" ng-r ...

AngularJS modifying shared factory object across controllers

Is it possible to update the scope variable pointing to a factory object after the factory object has been updated? In cases where there are 2 angular controllers sharing a factory object, a change made to the factory object by one controller does not re ...

When using Node Puppeteer, if the page.on( "request" ) event is triggered, it will throw an error message stating "Request is already being handled!"

I am currently utilizing puppeteer-extra in conjunction with node.js to navigate through multiple URLs. During each iteration, I am attempting to intercept certain types of resources to load and encountering the error below. PS C:\Users\someuser ...

Access NgModel from NgForm

Is there a way to access the NgModel of a FormControl retrieved from the NgForm.controls object within its parent form, or directly from the form itself? Upon form submission, I pass the form as a parameter to a custom function: <form #myForm="ngForm" ...

What makes it essential to use jasmine's runs and waitFor function?

My current task involves testing an asynchronous code snippet structured like this: randomService.doSomething().then(function() { console.log('The operation has been completed!'); }); Interestingly, I've noticed that the success messag ...

Verifying file types with HTML5 drag and drop feature

Is it possible to change the drop zone's background color to green or red based on whether the dragged payload contains supported file types (JPEG)? Do Gecko and Webkit browsers have the ability to determine the file type of drag and drop files? ...

When is the best time to access user credentials in the FirebaseUI authentication process?

Referring to a provided example on using firebase authentication with Next.js from the Next.js github, I have noticed that many projects I have studied incorporate createUserWithEmailAndPassword at some point. This function allows them to utilize user cred ...

IE Troubles: Timer Function Fails in Asp.Net MVC

I implemented the following code snippet: @Using Ajax.BeginForm("Index", New AjaxOptions() With { _ .UpdateTargetId = "AnswerSN", .HttpMethod = ...

In a REST api, what is the appropriate response for a property that is missing a value?

Is it better for a property with no value assigned to be returned as null, or should the REST API skip such properties entirely? Let's consider a user object example with first_name and last_name. (In the below example, last_name is not necessarily a ...

Tips for creating emissiveMap lighting exclusively in dimly lit spaces using three.js

Using three.js, I am able to render the earth with textures and add an emissive texture for city lights. However, I am facing a problem where even the light areas of the earth emit city lights. For example: https://i.sstatic.net/hZ1Cr.png Is there a way ...

Having trouble with one of the stubs not working while unit testing with ava and sinon for an API call

Looking for advice on a test case I'm struggling with. The function I need to test involves 2 upper layer promise functions. I have stubbed all three functions, the first two are working fine but the last one is not functioning as expected. classD: c ...

Error with the setInterval() method, function is not executing

UPDATED CODE SNIPPET: <script> $.ajaxSetup({ cache : false }); function fetchMessage() { $.get("php/getMessage.php?q=1" + "&" + Date.now(), function(data) { $("#typed").typed({ ...

Issue during Docker build: npm WARN EBADENGINE Detected unsupported engine version

Currently, I am constructing an image based on mcr.microsoft.com/devcontainers/python:0-3.11-bullseye. In my docker file, I have included the following commands towards the end: RUN apt-get update && apt-get install -y nodejs npm RUN npm install np ...

How to save array data to a text file using node.js

I have an array containing values that I want to write to a text file using the following code. while(filedataarr.length>0) { firstelement = filedataarr.shift(); //console.log(firstelement); fs.appendFile("D:\\Temp& ...

Guide to setting up a universal error handling system compatible with forkJoin in Angular 6

I recently implemented error handling in my app following the guidelines from the official Angular 6 tutorial in rest.service.ts ... return this.http.get(url).pipe(catchError(this.handleError)); } private handleError(error: HttpErrorResponse) ...

Embed a static label inside an input field that remains constant even while text is inputted, without using a placeholder. Crafted using HTML,

Take a look at the screenshot below - what you see on the left side is my current setup, while on the right side is the desired outcome achieved without any plugins or HTML5 attributes The left side scenario occurs when I have 2 input fields - one with th ...

Understanding special characters within a URL

Here is a URL example: postgres://someuser:pas#%w#@rd-some-db.cgosdsd8op.us-east-1.rds.amazonaws.com:5432 This URL is being parsed using the following code snippet: const url = require('url'); const { hostname: host, port, auth, path } = url.par ...