[英]Focus a NodeList element
NodeList
items do not have a focus
method. NodeList
项没有focus
方法。 However, I've seen a few articles written with literally nodeList[index].focus()
which must be incorrect, right?但是,我看过几篇用
nodeList[index].focus()
写的文章,这肯定是不正确的,对吧?
How do we focus the element from a NodeList?我们如何聚焦 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
NodeList
is not an narrow enough type; NodeList
不是一个足够窄的类型; you have to specify that it's a node list of HTMLElement
s.您必须指定它是
HTMLElement
的节点列表。 You can do this with the NodeListOf<HTMLElement>
type:您可以使用
NodeListOf<HTMLElement>
类型执行此操作:
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:请注意,您也可以让编译器推断正确的
nodeList
类型,而不必显式键入它:
let nodeList = el.nativeElement.querySelectorAll('a');
nodeList[0].focus();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.