Observe the classList object of the material element to obtain its properties

I am currently using the mat-autocomplete feature and I am trying to remove focus from the input after selecting an element without needing a click. The mat-focused class within the mat-form-field is responsible for focusing on the mat-auto-complete. By removing it from the mat-form-field, I was able to achieve this. However, there is a slight delay in setting the mat-focused class and I have been using setTimeout to wait for it to be set before removing it. Although this works, I believe there might be a better solution utilizing async functions, promises, observables, or other features provided by Angular Material instead of relying on setTimeout.

Component:

export class AutocompleteSimpleExample {
  myControl: FormControl = new FormControl();
  public matForm ;
  constructor(){

  }

  ngOnInit(){
    this.matForm =  document.getElementById("matForm") 
  }
  options = [
    'One',
    'Two',
    'Three'
   ];

  test(option){
    console.log(option)
    setTimeout(function(){
      this.matForm.classList.remove('mat-focused' )}, 100);
  }
}

HTML:

<form class="example-form">
  <mat-form-field class="example-full-width test" #matForm id="matForm">
    <input type="text" placeholder="Pick one" aria-label="Number" matInput [formControl]="myControl" [matAutocomplete]="auto" #textInput>
    <mat-autocomplete #auto="matAutocomplete" (optionSelected)="test($event.option)">
      <mat-option *ngFor="let option of options" [value]="option">
        {{ option }}
      </mat-option>
    </mat-autocomplete>
  </mat-form-field>
</form>

You can view the example on StackBlitz.

Answer №1

Avoid manually adjusting the CSS class. This approach is not in line with Angular's methodology.

Instead, utilize the framework itself by creating a view child element and triggering the blur event on it. You can see an example of this in action on this StackBlitz demo:

@ViewChild('textInput') textInput: ElementRef;  
test(option) {
  console.log(option.value)
  setTimeout(() => {
    this.textInput.nativeElement.blur();
  });
}

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

Tips for positioning your side navigation menu parallel to the page edge

Im looking to have the side navigation floated to the left as I scroll down the page. I tried using the sticky property, but it didn't work out. Here's a snippet of the code: .sticky-class { position: sticky; top: 30px; } This is how my HTML ...

The predicament with arranging arrays

I'm working with an array that looks like this: [ { "TaskID": 303, "TaskName": "Test1", "TaskType": "Internal", "Status": "Processing", "IsApproved": false, "RowNumber": 1 }, { "TaskID": 304, ...

Tips for enhancing the appearance of the dropdown scrollbar in PrimeNG

Just started exploring Angular and I've been struggling to customize the scrollbar on a PrimeNG dropdown. Does anyone have any tips or tricks to achieve this? Here is the HTML code: <p-autoComplete placeholder="- Select -" (onSelect)="onSelect(dh ...

Tips on automatically changing the background image every few seconds

As a newcomer to Angular and programming in general, I am facing an issue with changing the background image of my Page using the setInterval method. The intended behavior is for it to change every second, but for some reason, it changes much faster than t ...

Unable to assign to 'options' as it is not recognized as a valid property of 'p-multiSelect'

I am currently in the process of incorporating the datatable filter from primeng into my project. Here is the code snippet I have written: <p-column field="time" header="Time" [filter]="true" filterPlaceholder="&#xf0b0;"> <ng-template pTe ...

Error in NextJS with TypeScript when updating data in a useState variable

Recently, I started working with TypeScript, ReactJS, and NextJS, but I encountered a TypeScript error that I need help fixing. My current project involves using NextJS 14, server actions, and Prisma as the ORM for a university-related project. An issue ar ...

Send the latest cell parameters from the CellRendererFramework element to the main grid component

Within ag-grid, I am utilizing the cellRendererFramework to render a specific cell. By accessing the params property, I can retrieve the values of the cell from the parent grid component. However, I now have the need to update these params from my cellRend ...

How to immediately set focus on a form control in Angular Material without needing a click event

Currently working with Angular 9 and Material, we have implemented a Stepper to assist users in navigating through our workflow steps. Our goal is to enable users to go through these steps using only the keyboard, without relying on mouse clicks for contro ...

Choosing a specific row in Angular 5

I'm completely new to Angular, so please bear with me :) I have a collection of user data that is presented in the following format: https://i.sstatic.net/5UAIP.png Below is my current HTML structure: EDIT - ADDED CRUD BUTTONS : <!--Add ...

There was an error in Angular at core.js:6150 stating that the object is not iterable due to a

I am facing an issue in displaying the First Name of a user in an HTML file getFirstName(id: any){ this.users = this.afs.collection('users', ref => ref.where("uid", "==", id)).valueChanges(); this.users.subscribe(users => { ...

Is it possible to manipulate an Object within Object typescript?

My recent project involved working with React and Typescript to fetch data from an API. Once the data is fetched, it is saved as an object called coin. However, I encountered a situation where the data may not be fully loaded, resulting in coin being null. ...

Sending an HTTP post request to a server that is powered off results in an error on Android devices but strangely not on iOS devices

I am currently utilizing Angular 2 and Ionic 2 for my project. To test how the offline mode is handled, I intentionally shut down the server that my app sends requests to. For this project, I have created a Custom HTTP Service using import { Http, Header ...

Differentiate between minimum and maximum values on ion-range sliders with discrete color options

I am currently working on customizing the theme of my ionic app, specifically trying to assign different colors to the min and max knobs on an ion-range component. At the moment, I am only able to apply a single HTML property called "color" to the selector ...

Utilizing ControlValueAccessor for accurate data validation

I've developed my own input fields using the ControlValueAccessor. How can I retrieve validation information within this component? Feel free to check out an example here: https://stackblitz.com/edit/angular-ngmodel-valid?file=src/app/text-input.com ...

When adding new elements to an array, the IDs of all objects become identical

When running the code below: dietDay.meals.forEach((meal) => { meal.mealProducts.forEach((mealProduct) => { if ( mealProduct.product.id && this.fetchedProductIds.includes(mealProduct.p ...

Guide to utilizing selenium for triggering Angular events (ng-click)

Attempting to invoke an angular ng-click through selenium is proving to be quite challenging. The focus lies on this particular snippet of javascript: <span class="col" ng-click="getHope(1,'pray','smile')">100%</span> This ...

The generics in TypeScript for Parameters<URLS[T]> and the corresponding URLS[T] are not compatible

In the code below, I am encountering a type error: const urls = { inviteNewUser: ({teamId, intent = 'invite'}: {teamId: string; intent?: Intent}) => `/magic-link?intent=${intent}&teamId=${teamId}`, resetPassword: ({intent = 'r ...

The NestJS HttpService is encountering issues with API calls when an Interceptor is implemented

When using NestJS API App with HttpService to call another API, the functionality works successfully without any custom interceptors. However, the issue arises when attempting to view the response from the called API. The following code snippet showcases ...

Limiting the display of every item in Angular ngFor

I'm currently working with Angular and I have the following code in my component.html: <div class="card" *ngFor="let item of galleries;" (mouseenter)=" setBackground(item?.image?.fullpath)" (mouseover)="showCount ...

Tips on incorporating dynamic expressions within ngFor loops?

Is there a way to dynamically display specific properties from objects in an array (list: any[]) within an *ngFor loop in Angular? I am currently working on a component called ListComponent that is responsible for rendering a list of items. The parent com ...