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

Troubleshooting issues with accessing the _id property using Typescript in an Angular application

Encountering an Angular error that states: src/app/components/employee/employee.component.html:67:92 - error TS2345: Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is ...

React Quill editor fails to render properly in React project

In the process of developing an application in Ionic React, I am in need of a rich text editor that can save data on Firestore. Despite initializing the editor as shown below and adding it to the homepage component, it is not rendering correctly although i ...

Angular 7 form does not automatically disable the button upon initialization

My current challenge involves disabling a button until a form is completely filled out. Surprisingly, everything works perfectly in Chrome and Firefox, but IE11 seems to be causing some issues. Below is the relevant code snippet: <div class="col-12"> ...

Mastering the Art of Mocking Asynchronous Methods in Node.js Using Jest

I have the following files: |_ utils.js |_methods.js I am currently conducting unit testing for rest.js methods, where the content of the file is as follows: methods.js import Express from 'express' import { add_rec } from './utils' ...

Utilizing Anglar 16's MatTable trackBy feature on FormGroup for identifying unaltered fields

In my application, I am working with a MatTable that has a datasource consisting of AbstractControls (FormGroups) to create an editable table. At the end of each row, there are action buttons for saving or deleting the elements. My goal is to implement tr ...

Using the recommended Prettier plugin for TypeScript in ESLint is causing issues with the ability to use the override keyword

Software Versions: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6a0f190603041e2a5d445958445a">[email protected]</a> <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7000021504041915023 ...

Do not send the Angular 2 HTTP request with headers

As someone new to Angular2, I am working on building a data service and trying to include headers in each request. Here is my attempt at adding headers, but for some reason they are not being sent: import { Injectable } from '@angular/core'; im ...

What is the best approach for unit testing with a subscribe in Angular 5?

import { Component, Input, OnInit } from '@angular/core'; import {DataplansDetails} from '../../models/dataplans-details'; import * as _ from "lodash"; @Component({ selector: 'jsonform', templateUrl: './jsonform.comp ...

The system encountered an error while trying to access the property 'enabled' of an undefined object

When working on a reactive form in my code, I need to ensure the values are properly set for the controls. ngDoCheck() { setControlValues(); } ngChanges(changes: SimpleChanges): void { setControlValues(); } private setControlValues() { try { ...

Using the currency pipe with a dynamic variable in Angular 2

My application utilizes CurrencyPipe, The current implementation is functional, <div class="price">{{123 | currConvert | currency:'USD':true:'3.2-2'}}</div> Now, I need to dynamically pass the currency from a model varia ...

The Angular custom modal service is malfunctioning as the component is not getting the necessary updates

As I develop a service in Angular to display components inside a modal, I have encountered an issue. After injecting the component content into the modal and adding it to the page's HTML, the functionality within the component seems to be affected. F ...

Buttons for camera actions are superimposed on top of the preview of the capacitor camera

I am currently using the Capacitor CameraPreview Library to access the camera functions of the device. However, I have encountered a strange issue where the camera buttons overlap with the preview when exporting to an android device. This issue seems to on ...

Maintaining checkbox selection while switching pages in Angular

When I try to edit the settings for accepting payments in all currencies under the "Pricing" component, the checkbox is unchecked every time I return to the "General" section. How can I prevent this from happening and keep the checkbox checked? Refer to ...

Should the method of creating a Dropdown with Angular be considered a poor practice?

I've recently dived into Angular and successfully created my first dropdown using it, which is working great. However, I'm a bit concerned about the number of comparisons being made and wondering if this approach is considered bad practice. The ...

Exploring the use of Observables in Angular 2 services

Ensuring the seamless transfer of data between components is crucial in Angular development. One common way to achieve this is by utilizing observables. Let's take a look at how observables are implemented in a service: import { Injectable } from &ap ...

Exclude<Typography, 'color'> is not functioning correctly

Take a look at this sample code snippet: import { Typography, TypographyProps } from '@material-ui/core'; import { palette, PaletteProps } from '@material-ui/system'; import styled from '@emotion/styled'; type TextProps = Omi ...

TypeScript generic types allow you to create reusable components that

function genericIdentity<T>(arg: T): T { return arg; } let myGenericIdentity: <U>(arg: U) => U = genericIdentity; I see that the 'genericIdentity' function is accepting an argument of a generic type. However, I am unsure about ...

Can we programmatically switch to a different mat-tab that is currently active?

Looking to programmatically change the selected mat-tab in a TypeScript file. I came across a solution for md-tab, but I need it for mat-tab. I attempted the suggested solution without success. Here's what I tried: HTML <button class="btn btn- ...

Sweetalert seems to have hit a roadblock and is not functioning properly. An error has been detected in its TS file

Currently, I am responsible for maintaining an application that utilizes Angular 7.0.7 and Node 10.20.1. Everything was running smoothly until yesterday when my PC unexpectedly restarted. Upon trying to run ng serve, I encountered the following error: E ...

Pyramid CORS does not support the PUT and DELETE HTTP methods

My current issue involves the pyramid framework. I have added a function to pyramid add_cors_headers_response_callback(event): def cors_headers(request, response): response.headers.update({ 'Access-Control-Allow-Origin': &ap ...