Reputation: 5934
NodeList
items do not have a focus
method. However, I've seen a few articles written with literally nodeList[index].focus()
which must be incorrect, right?
How do we focus the element from a NodeList?
let nodeList:NodeList = el.nativeElement.querySelectorAll('a');
...
nodeList[0].focus(); // Property 'focus' does not exist on type 'Node'
(nodeList[0] as HTMLElement).focus(); // doesn't work
Upvotes: 2
Views: 1005
Reputation: 16576
NodeList
is not an narrow enough type; you have to specify that it's a node list of HTMLElement
s. You can do this with the NodeListOf<HTMLElement>
type:
let nodeList: NodeListOf<HTMLElement> = el.nativeElement.querySelectorAll('a');
nodeList[0].focus();
Note that you could alternatively let the compiler infer the correct type of nodeList
and avoid having to explicitly type it:
let nodeList = el.nativeElement.querySelectorAll('a');
nodeList[0].focus();
Upvotes: 2