Set the mat-option as active by marking it with a check symbol

Currently, I am utilizing mat-autocomplete. Whenever a selection is made manually from the dropdown options, the chosen item is displayed with a distinct background color and has a checkmark on the right side.

However, when an option in the dropdown is set programmatically, it does not appear highlighted. To achieve this, I am using the setValue() method to set the value programmatically.

Answer №1

1- Create a new attribute in your dataset:

preferences: {name:string,isActive:boolean}[] = [{name:'A',isActive:false},{name:'B',isActive:false},{name:'C',isActive:false}];

2- Assign the [displayWith] property to mat-autocomplete for handling value manipulation with mat-option

<mat-autocomplete requireSelection #auto="matAutocomplete"  [displayWith]="displayData()">

3- Implement a function to control data binding in mat autocomplete

displayData = () => (value: string): string =>{return !value ? this.preferredData :  value}

preferredData represents the default value e.g.

this.preferredData = "D"

4- Utilize ngClass directive on mat-option

<mat-option  [ngClass]="{'activeOption': pref.isActive}" 

then

.activeOption {background-color: var(--selected-option-color)}

5- Apply the new style to options with existing data and include a checkbox within mat-option tag if needed.

6- Update the preferences object's isActive property value to true | false for managing ngClass changes. Use

(optionSelected)='updateMethod($event)'
on mat-autocomplete to modify the preferences object property.

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

Utilizing Vue and Typescript for efficient dependency injection

After attempting to use vue-injector, I encountered an issue as it was not compatible with my version of Vue (2.6.10) and Typescript (3.4.5). Exploring other alternatives, there seem to be limited options available. Within the realm of pure typescript, t ...

Looking up the Vue.js type definitions in TypeScript

I'm currently working on enabling type checking in my Vue.js code (v2.2.1). My initial goal is to ensure that this specific line compiles with TypeScript (meaning I want the Vue class to be properly identified): var app = new Vue(); I've discov ...

Changing the content of an HTTP response with the help of RXJS

My API response includes a payload with various details about the queue and its customers. Here is an example of the payload: { "uid": "string", "queue": { "size": 0, "averageWait ...

Whenever comparing the types 'string[]' and 'DeliveryTypeEnum', this condition will consistently result in 'true' as there is no intersection between the two. This is highlighted by the error code ts(2367)

Hello everyone, I'm a junior developer and could use some assistance if (query.deliveryType && query.deliveryType != DeliveryTypeEnum.EITHER) { search.push({ terms: { "deliveryType.keyword&q ...

Modify the standard localStorage format

I'm encountering a dilemma with my two applications, located at mysite.com/app1 and mysite.com/app2. Both of these apps utilize similar localStorage keys, which are stored directly under the domain "mysite.com" in browsers. This setup results in the l ...

Enabling non-declarative namespaces in React using Typescript: A beginner's guide

I'm diving into the React environment integrated with Typescript, but I still have some confusion about its inner workings. I really hope to receive thorough answers that don't skip any important details. I came across a solution that involves d ...

Having trouble injecting ActivatedRouteSnapshot into the component

Struggling to inject ActivatedRouteSnapshot into a component, encountering errors when trying to access query params. Here is the error stack trace: "Error: Can't resolve all parameters for ActivatedRouteSnapshot: (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?). a ...

Customize stepper background color in Angular Material based on specific conditions

I am working on a project using Angular Material and I want to dynamically change the color of the stepper based on different states. For example: state: OK (should be green) state: REFUSED (should be red) Here is what I have done so far: <mat-horizo ...

Why is my custom Vuelidate validator not receiving the value from the component where it is being called?

On my registration page, I implemented a custom validator to ensure that the password meets specific criteria such as being at least 12 characters long and containing at least one digit. However, I encountered an issue where the custom validator was not r ...

The PrimeNG FullCalendar feature seems to be malfunctioning and cannot be located

I've been working on integrating a FullCalendar module into my Angular 7 project. Despite following the steps provided in this link, I haven't had any luck: After executing this command: npm install <a href="/cdn-cgi/l/email-protection" clas ...

Storing a reference globally in React and Typescript: Best practices

In my application, I have multiple instances of a specific component called <Item>. Each <Item> needs to display a dynamic tooltip when hovered over. To achieve this, I am utilizing semantic-ui-react and its Popup component. The conventional m ...

I encountered an issue while trying to install the latest version of AngularFire, receiving an error

Recently, I initiated a new Angular Material project and encountered the following errors: moblizeit@Vikrams-MBP scanbuddyadmin % ng add @angular/fire@latest ℹ Using npm as the package manager ⚠ There are unmet peer dependencies within the package. Add ...

Capturing the httpClient response within a service using rxjs

My application has a LoginComponent which includes a form for user credentials, and a LoginService responsible for making API calls using an httpClient. In my services, I usually return the call so that I can subscribe to it within my component as needed. ...

Using TypeScript, apply an event to every element within an array of elements through iteration

I have written the code snippet below, however I am encountering an issue where every element alerts the index of the last iteration. For instance, if there are 24 items in the elements array, each element will alert "Changed row 23" on change. I underst ...

What is the best way to include an object in a document before sending it back?

I am facing a challenge that involves retrieving data from Firestore using angularfire. Once I fetch a collection, I need to iterate through each document in the collection and then make a separate request to Firestore to get additional document values. Th ...

Subscribing to ngrx store triggers multiple emissions

Currently, I have an app with a ngrx store set up. I am experiencing an issue where, upon clicking a button, the function that fetches data from the store returns multiple copies of the data. Upon subsequent clicks, the number of returned copies grows expo ...

Can you explain the functionality of this Angular CLI instruction?

Can you explain the function of this command in the Angular command line? npx ng g s weather --flat false Referenced in: Angular 6 for Enterprise Ready Web Applications, page 61 ...

Learn how to leverage Angular 4's ngComponentOutlet to dynamically pass values from an array

Check out this Plunker demo: https://plnkr.co/edit/JvXBLOVaeaYO5bmMQa6a?p=preview In the Plunker example, I have created 3 boxes using an ngFor loop from an array. Each box has its own event listener attached to it. The goal is to generate a component whe ...

How do I disable split panel on Ionic 2 login page exclusively?

I have successfully implemented the split-pane feature in my app.html file. However, I am facing an issue where the split pane is being applied to every page such as login and SignUp. Can someone please guide me on how to restrict the split pane function ...

Why is it that the component passed in props fails to function properly when invoked as a function? React is signaling a shift in the order of Hooks being called

Here is a simple example I've prepared to illustrate how I am passing a component and then calling it like a function, as well as another example where it works just by calling it normally. You can switch between the working and not working examples b ...