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.