The autofocus feature is a one-time deal

When the Input is clicked, autofocus works only on the first instance - therefore the 'list-formatter' (autocompleListFormatter) is initiated only once.

https://i.sstatic.net/z1GC4.gif

Is there a way to have 'autofocus' focus multiple times?

dropdown.component.html

<form [formGroup]="myForm" class="">
  <div class="form-style">
    <input
      autofocus
      [list-formatter]="autocompleListFormatter"
      type="text"
      class="form-control"
      ngui-auto-complete
      formControlName="costCenter"
      [source]="dropdownData"
      value-property-name="id"
      display-property-name="name"
      [(ngModel)]="value"
    />
  </div>
</form>

dropdown.component.ts

export class DropdownComponent implements OnInit, AgEditorComponent {
  @Input() name: String;

  public dropdownData = ColumnData[0].cellEditorParams.values;
  public myForm: FormGroup;
  public selected;
  value: any;
  oldValue: any;
  params: any;
  public container;
  constructor(private builder: FormBuilder, private _sanitizer: DomSanitizer) {}

// ****DROPDOWN****** //
  autocompleListFormatter = (data: any) => {
    let html = `<span>${data.name}</span>`;
    return this._sanitizer.bypassSecurityTrustHtml(html);
  };

  refresh(params: ICellEditorParams) {
    this.params.api.refreshCells();
    return true;
  }

  getValue(): any {
    if (this.value === '') {
      this.value = this.oldValue;
    }
    return this.value;
  }

  agInit(params: ICellEditorParams) {
    this.value = params.value;
    this.oldValue = this.value;
    this.value = '';
    return this.value;
  }

  ngOnInit() {
    this.myForm = this.builder.group({
      costCenter: ''
    });
  }
}

STACKBLITZ

Update: It has been suggested to use an auto-focus directive. The directive was added to the code but it is not functioning properly

Answer №1

One way to achieve this is by obtaining a reference to the input element and using the focus method.

Here is the template:

<form [formGroup]="myForm" class="">
  <div class="form-style">
    <input
      defFocus
      [list-formatter]="autocompleListFormatter"
      type="text"
      class="form-control"
      ngui-auto-complete
      formControlName="costCenter"
      [source]="dropdownData"
      value-property-name="id"
      display-property-name="name"
      [(ngModel)]="value"
      #agInput
    />
  </div>
</form>

And here is the component code:

export class DropdownComponent implements OnInit, AgEditorComponent {

  @Input() name: String;
  @ViewChild('agInput', { static: true}) public elm: ElementRef;

  ....

  setFocus() {
    this.el.nativeElement.focus();
  }

   ngAfterViewInit() {
     setTimeout(() => {
        this.setFocus();
     }, 500);
   }
}

Check out the demo 🚀

You can also view my answer on fixing focus problems here, where I provide a solution using a custom directive.

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

*ngFor is not rendering

I understand that this question is frequently asked, but the usual solutions don't seem to be effective in this case. Here is my code snippet: export class CourseReviewFormComponent implements OnInit { form: FormGroup questionnaire: string[] = [] ...

Tips for customizing the appearance of a leaflet popup in your own unique style

I've been attempting to style a marker popup, but for some reason, the styles aren't being applied to the popup. Additionally, I'm having trouble adding a button to the popup. import { Map, marker} from "leaflet"; const popupOptions = { ...

Having trouble accessing child pages using the router

In my Angular 2 application, I have implemented navigation successfully with the following routes: { path: 'layer1/layer2', component: C2 } } { path: 'layer1/layer2/layer3', component: C3, canDeactivate: [CanDeactivateGuard] } }, With ...

What is the best way to apply CSS to a single component in React?

I want to import ignite-ui styles specifically for a single component. Component: @Component({ selector: 'app-detailed-report', templateUrl: './detailed-report.component.html', styleUrls: ['./detailed-report.component.css& ...

insert a gap between two elements in the identical line

Is there a way to create spacing between two text fields in the same row? I have tried using margins, paddings, and display flex in the css file but haven't been successful. import "./styles.css"; import TextField from "@material-ui/cor ...

Tips for aligning the text horizontally in an input field with a neighboring element

Hello amazing community, I'm searching for a neat way to align the text of an element horizontally with that of an Angular Material input field. Here is the code I am using: <div style="display: flex"> <div>Greeting: </div> ...

Encountering an error while attempting to modify the state of an array of objects in a React Typescript

Recently delving into Typescript, I encountered an issue while attempting to insert a new object into the array within React state. The error message reads as follows: Type '{ name: string; address: string; }[] | null' is not an array type.ts(246 ...

Use contextual type when determining the return type of a function, rather than relying solely on

When using Typescript 2.2.2 (with the strictNullChecks option set to true), I encountered an unexpected behavior. Is this a bug or intentional? interface Fn { (value: any): number; } var example1: Fn = function(value) { if (value === -1) { ...

order by truthiness

I am working with an array of the following class: export class Tests { id: number; name: string; createdAt: any; succress: boolean; constructor(id: number, name: string, createdAt: any, success: boolean) { this.id = id; this.name = nam ...

The error message "element is not defined" is indicating an issue related to the cordova-plugin-google

In my current project using Ionic 3, I decided to implement map-related features by incorporating the Google Maps plugin recommended by the Ionic Team. This specific plugin serves as a wrapper around cordova-plugin-googlemaps. Following the steps outlined ...

Innovative solution for detecting and replacing undefined object properties in Angular 2 with TypeScript

After encountering the issue of core.umd.js:3523 ORIGINAL EXCEPTION: Cannot read property 'fullName' of undefined I realized that the Exception stemmed from a Template trying to access a specific property: {{project.collaborators["0"]["fullN ...

Setting up a front-end framework on top of a Flask backend: A step-by

Recently, I've been eager to create a small web application geared towards managing data - showcasing lists of records, editing information, and adding new entries. As the backbone of my project, I am utilizing Flask as my backend framework and simult ...

Guide to Sorting Arrays of Objects in Angular 8 by Matching Nested Object Values

I am receiving an API response within the getClusterByName() function, I need to search through an array of objects based on the region value passed from the changeRegion function. For example - if I pass '1UL Africa' or 'New Test' or ...

The dropdown component in React TypeScript may have an undefined object

I'm currently working on a dropdown component, but TypeScript is throwing errors for the options.map and selectedOption.title cases: import React, { useRef,useState, useEffect } from "react"; import useToggle from '../hooks/useToggle&ap ...

Is there a way to stop a click event on an Angular component's host from triggering?

Currently, I'm developing an Angular component that adds extra functionality to a native <button> element. In this component, I would like to mimic the behavior where buttons do not trigger a click event if they are disabled. For instance: < ...

Struggling with a Nextjs Stripe issue? The expected signature for payload does not match any found signatures

Struggling to integrate data from Stripe check out events into my orders database, facing issues with finding the signature while testing the web hook. Check out route: app/api/webhooks/checkout/route.ts import Cors from "micro-cors"; import { h ...

Guide on crafting a query with typeorm query builder to extract specific data from the database

I'm a beginner with typeorm in nodejs/nestjs and I'm struggling to create a query to filter course data by instructor's firstname and lastname, course name, and subject. I've tried using 'where' and 'orWhere' but can ...

Compilation in TypScript has encountered an error - The use of 'await' expressions at the top level is restricted unless the 'module' option is appropriately configured

When attempting to generate dynamic tests based on data from an excel sheet using TypeScript with TestCafe, everything runs smoothly... until I try to create the dynamic "tests" within the "fixture." This is my code: import { fixture, test, GFunctions } f ...

The useRef function is malfunctioning and throwing an error: TypeError - attempting to access 'filed2.current.focus' when 'filed2' is null

I'm attempting to switch focus to the next input field whenever the keyboard's next button is pressed. After referring to the react native documentation, it seems that I need to utilize the useRef hook. However, when following the instructions f ...

Connect your Angular project on your local system

Having some trouble connecting my angular 13 project as a ui-component library. Successfully built the project and have the package stored in a dist folder. I then linked it to my primary project (angular 14) using "yarn link" and confirmed its presence as ...