What is the best way to automatically focus on my input when the page loads?

My Angular application has a 'slider' component that loads 3 child components utilizing ng-content. The first child component contains a form, and I am trying to focus on the first field upon page load. Despite setting up ViewChild correctly to reference the nativeElement, the focusing functionality only works when triggered manually. Unfortunately, I have been unable to achieve the focus on the initial page load.

I suspect that the issue lies in how the child component is loaded using ng-content, but I am struggling to find a solution.

Here is the control in my component template:

<label for="name" class="form-label">Name</label>
<input type="text" class="form-control" id="name"
     required
     [(ngModel)]="model.name" name="name"
     #name="ngModel">
<div [hidden]="name.valid || name.pristine" class="alert alert-danger mt-2">
Name is required
</div>

And here is the component logic:

import { Component, OnInit, AfterViewInit, Output, EventEmitter, ViewChild, ElementRef } from '@angular/core';
import { NgForm } from '@angular/forms';

@Component({
  selector: 'app-definitions',
  templateUrl: './definitions.component.html',
  styleUrls: ['./definitions.component.scss']
})
export class DefinitionsComponent implements OnInit, AfterViewInit {
  @ViewChild('name', { read: ElementRef }) ingredientName: ElementRef = {} as ElementRef;

  ngAfterViewInit(): void {
    console.log('el', this.ingredientName.nativeElement);
    this.ingredientName.nativeElement.focus();
  }
}

Despite logging the element successfully in the console, the focus does not occur when the document loads. I suspect that the issue may be related to how the component is loaded via ng-content within its parent component. However, I cannot determine why this would impact the behavior.

I have also attempted to use setTimeout, but it had no effect.

Interestingly, wrapping

this.ingredientName.nativeElement.focus()
in a method and calling it through, for example, a button click on the component results in the desired focus. However, it still does not work on page load.

If anyone has any insights into why this functionality fails, please share your thoughts.

Thank you.

UPDATE: It appears that this issue is specific to Microsoft Edge as the functionality works fine in Chrome.

Answer №1

Consider setting the tabindex to 0

<input tabindex="0"
     type="text" class="form-control" id="name"
     required
     [(ngModel)]="model.name" name="name"
     #name="ngModel">

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

Generating a d.ts file for images in Typescript using automation techniques

Currently, I am working on a React application that utilizes TypeScript and webpack. I am aware that in TypeScript, when importing an image file, it is necessary to create a d.ts file in the current directory and include the following code: // index.d.ts ...

Determining the position of the selected option in an Angular 2 Select menu

Is there a way to retrieve the position of the selected option in a similar manner to the index of a table? Example for a table: <tr *ngFor="let car of cars; let i = index" (click)="showTabs(i)"> <td>{{i+1}}</td> </tr> I am lo ...

Angular failing to recognize the && operator

I have a button that opens a dialog with the blockui feature. I am trying to close the dialog and set the blockui boolean variable to false in order to stop blocking the UI. However, in my HTML code (click)="blockedDialog=false && displayAddDialog=false", ...

What is the best way to implement a Promise Function within a For loop?

Here is a function called sendEmail: public async sendEmail (log: LogMessage): Promise<void> { nodemailer.createTestAccount(async () => { return ServiceFactory.getSystemService().getNetworkPreferences().then(async (networkPreferences) => ...

Tips for implementing <mat-progress-bar> in .ts file when making API service requests with Angular

I'm currently utilizing an API call to retrieve an image from a service, and I would like to display a progress bar while the image is being fetched. It seems that I need to incorporate the progress bar within the service as the image data is returned ...

In search of assistance with resolving a React Typescript coding issue

I need help converting a non-TypeScript React component to use TypeScript. When attempting this conversion, I encountered the following error: Class 'Component' defines instance member function 'componentWillMount', but ext ...

Setting the Default Value for Dropdown Options in Angular 2

Back in the Angular 1 days, I had a trick up my sleeve for setting the default option on a dropdown menu: <select data-ng-model="carSelection" data-ng-options = "x.make for x in cars" data-ng-selected="$first"> </select> But now, in ...

Manage and execute a sequence of multiple actions with Redux-Observable

Utilizing redux-observable, my goal is to generate multiple WORK actions from a single epic. Here's what I have so far: ( action$, state$ ) => { return action$.pipe( ofType( 'SPAWN' ), flatMap( action => { retu ...

Is there a solution for the error message "Operator '+' cannot be used with types 'string | number' and 'string' | number'"?

Here's the scenario: I'm encountering an issue where I am invoking a function within another function. This inner function has the capability to return either a string or a number, and my goal is to combine that with another value. However, I kee ...

Deactivate the FormGroup by implementing Validators

In my form, I have a checkbox group named formArray within my checkboxForm. The task at hand is to disable the submit button if none of the checkboxes are checked. To achieve this, I created a custom validator for my checkboxForm and here is my approach: ...

The React component was not able to receive any children as input

My Typescript-written React component is called GradientText.tsx: import React, { ReactNode } from "react" import { cn } from "@/lib/utils" const typeMap = { h1: "h1", h2: "h2", p: "p", } inte ...

Common Errors in Angular 2 due to TSLint

I am encountering multiple errors in my code. I am using Angular 2 with TSLint: constructor(http: Http) { this.http = http; --> let currentUser = JSON.parse(localStorage.getItem("currentUser")); this.token = currentUser && currentUser.t ...

Unable to retrieve npm repository from GitHub

I've been grappling for approximately 2 hours to integrate a repository into my angular project without success. Here's the link I've been trying: https://github.com/cmelange/ECL-3D-Components#ecl-3d-components. Despite previously having i ...

Guide to transforming a TaskOption into a TaskEither with fp-ts

I have a method that can locate an item in the database and retrieve a TaskOption: find: (key: SchemaInfo) => TO.TaskOption<Schema> and another method to store it: register: (schema: Schema) => TE.TaskEither<Error, void> Within my regis ...

Autocomplete search from a distance

I am currently learning Angular and trying to create an autocomplete form with content that is filtered on the back-end. I have defined a class and Interface for Terminal: export class Terminal { constructor( public id: number, public name: ...

Angular 2 offers the ability to crop and save images effortlessly

Utilizing ngImgCrop, I have been able to upload images and crop them successfully. Now, I am trying to figure out how to save the result-image from <img-crop image="myImage" result-image="myCroppedImage"></img-crop> to a folder in ASP.NET MV ...

What is the best approach for initializing and adding dataset in a database using Nest.JS when launching the application for the first time?

In managing my database, I have multiple tables that require default information such as categories, permissions, roles, and tags. It is crucial for me to ensure that this exact information has consistent IDs whenever the application is freshly launched on ...

Organize items within an array based on dual properties rather than a single one

Here is an array of objects that I would like to group based on certain keys (JSON format): [ { "name": "john", "lastName": "doe", "gender": "male" }, { "name": &qu ...

Top recommendation: Utilizing Typescript to allow a customer to enhance an application using their own tailored code

Our application framework is built on Angular 9, providing customers the ability to customize applications with different fields and layouts. This functionality works smoothly. However, we now face a situation where a customer wants to incorporate special ...

The Angular Progressive Web App functions properly in ng serve mode, but encounters issues when running with http-server

I'm developing a Progressive Web App (PWA) using Angular. Everything was functioning smoothly until out of nowhere, I started encountering a 404 Error whenever I tried to navigate to a new component while serving in dist/project with http-server. Surp ...