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

Encountering an issue with Typescript Vue class-based components in Laravel Mix: issue arises when attempting to set property 'render' on an undefined object

I have been using Laravel Mix to compile my Vue components, incorporating TypeScript and class-based components. Each class is exported from the component, and every component is required by the context in the main application script. However, during rende ...

Converting a string[] to an EventEmitter string[] in Angular 4 with TypeScript: Step-by-step guide

Programming Language: Typescript – written as .ts files Development Framework: Angular 4 I'm currently working on an application that is supposed to add chips (similar to tags in Angular 1) whenever a user types something into the input box and hi ...

Testing the unit with a customized header in the interceptor

I've been struggling to execute a unit test within an Angular 6 interceptor, but despite numerous attempts, I keep encountering the following error: Error: Expected one matching request for criteria "Match by function: ", found none. I'm rela ...

What is the process for updating information once the user has verified their email address on Supabase using Next.js

After a user signs up using a magic link, I want to update the profiles table in my database. Below is the code snippet I am currently using: Login.tsx import { useState } from "react"; import { supabase } from "../lib/initSupabase"; c ...

typescriptWhat is the syntax in TypeScript for creating a prototype of a multidimensional

I'm currently working on implementing additional methods for a 2D array using TypeScript. Adding methods to a 1D array is straightforward, as shown below: interface Array<T> { randomize(); } Array.prototype.randomize = function () { ...

Unable to determine all parameters for Angular's DataService

I have been working on developing a versatile service and came across an informative article: https://medium.com/@krishna.acondy/a-generic-http-service-approach-for-angular-applications-a7bd8ff6a068 that guided me in creating my DataService. Here is a snip ...

Tips for utilizing chodorowicz / ts-debounce effectively

Looking to utilize the debounce function provided by the ts-debounce package (available at here) in my typescript project. However, struggling to find a concrete example of its usage in typescript. Would greatly appreciate any help or guidance on this ma ...

Reasons why a functional component may not trigger a rerender after a state change using useReducer()

When using react Hooks, specifically useReducer, I found that although the state changes, the functional component does not rerender. Additionally, when trying to open the drawer by pressing a button in the menu, even though the state changes the drawer re ...

What could be the reason behind the login button not triggering the console message display?

I've decided to delve into web server development on my own and have been tweaking a GitHub repository for ExpressJS with Typescript that I stumbled upon. My initial goal is simple - just to have something displayed on the console when I click the log ...

Having trouble installing Angular CLI using npm command

After diligently following the steps outlined in the documentation here to install the Angular CLI, I encountered an issue. Upon running the command $ npm install -g @angular/cli in an empty directory, I was met with the following error message: npm ERR! ...

Is there a way to access a specific argument in yargs using typescript?

The idea behind using yargs is quite appealing. const argv = yargs.options({ env: { alias: 'e', choices: ['dev', 'prod'] as const, demandOption: true, description: 'app environment&apos ...

the input parameter is not being passed to the component

I need assistance with creating an inline input edit component. The component is loading correctly, but it seems like the @Input() variables are always returning undefined. index.html ... <app-inlineinput [name]="username" [fi ...

How can a parent component update a child component's prop value in VUE?

I'm facing an issue with managing dynamic props in Vue with TypeScript. Below is my parent component: <script setup lang="ts"> const friends = [ { id: "emanuel", name: "Emanuella e", phone: "08788 ...

Event-Propagation in Angular 5 with mat-expansion-panel within another component

In my project, I am facing a challenge where I need to create multiple mat-expansion-panels within one mat-expansion-panel. Everything works fine except for the issue that when I try to open a child-panel, it triggers the close-event of the parent-panel. ...

The Angular route successfully navigated to the page, but the HTML content was not

Whenever I select the Home option in the navigation bar, it takes me to the home URL but doesn't display the HTML content. Below is my app.routing.module.ts code: import { Component, NgModule } from '@angular/core'; import { RouterModule, Ro ...

Creating an Angular project with two different base-href configurations

Angular CLI: 7.2.3 Node: 10.14.1 OS: darwin x64 Angular: 7.2.2 Currently, my index.html file includes a base href set to <base href="/" /> and the application runs at http://localhost:port/ I am wondering if there is a way for my app to run both at ...

Verify internet connectivity with Ionic

Seeking a reliable method to accurately detect whether a mobile device is truly online and connected to the internet. One approach I have explored involves utilizing an http interceptor: if (navigator.connection.type != Connection.NONE) alert("you'r ...

A layout featuring nested buttons and links within a card element, utilizing the power of Link in NextJs

After extensive searching on S.O., I have been unable to find a solution that works flawlessly. The issue at hand involves a card component in a NextJs application that is encompassed within a <Link> tag. Additionally, there is another <Link> t ...

Create a new data structure in TypeScript that stores multiple values in a

For my TypeScript project, I came across a situation where I needed to utilize Promise.all(...) to handle an array of multiple items: Promise.all( firstRequest, secondRequest, ..., nthRequest ) .then((array : [FirstType, SecondType, ..., NthType]) ...

When I attempt to return an object from a function and pass the reference to a prop, TypeScript throws an error. However, the error does not occur if the object is directly placed in

Currently, I have the following code block: const getDataForChart = () => { const labels = ['January', 'February', 'March', 'April', 'May', 'June', 'July']; const test = { ...