Search code examples
angulareventsevent-handlingfocus

Listen to focus event in child component - handler doesn't capture focus event


I'm using Angular 16 - a parent component consumes a child component - the parent component is as follows

parent.component.html

<app-gotoitem #initialFocusComponent (initialFocusNativeElementFocus)="focusHandler($event)"></app-gotostudent>

parent.component.ts

@ViewChildren('initialFocusComponent') initialFocusComponents: QueryList<any>;
...
focusHandler(e) {
  console.log("do something");
}
...
this.initialFocusComponents.first.setFocus();

In my child component (gotoitem)

child.component.ts

@Output() initialFocusNativeElementFocus = new EventEmitter();
@ViewChild('initialFocus') initialFocus: ElementRef;
...
fromEvent(this.initialFocus.nativeElement, 'focus') //(B)
    .pipe(take(1))
    .subscribe(elem => {
    this.initialFocusNativeElementFocus.emit(); //(C) <--this doesn't get executed
});
...
public setFocus(): void {
  this.initialFocus.nativeElement.focus(); //(A)
}

However after the child executes the ".focus()" statement (A), the 'focus' event listener (B) doesn't capture the 'focus' event - and hence the 'emit()' (C) is never executed.

I can see the focus event handler attached to the desired HTML element (which this.initialFocus.nativeElement points to, which is a kendo-dropdownlist) - however the focus event listener has two events attached (the first refers to the "document" element [setup via zone.js], the second refers to the element pointed to by this.initialFocus.nativeElement) - see below

Event Listeners

If I manually delete the "document" event handler and focus on the element in question the 'focus' handler captures the event and the 'emit()' is executed

How is this scenario normally handled - regardless of whether the "document" event handler is there or not I need the focus event I have defined to also run - or do I need to remove the "document" event handler - if so how ?

Many thanks


Solution

  • I resolved the issue by listening to the focusin event rather than the focus event. The problem was because the focus event doesn't bubble whereas the focusin does