Javascript #选择器仅适用于根元素,不适用于角元素中的子元素
当我使用下面的id为根元素(应用程序组件)定义选择器时,我对选择器感到困惑,我能够呈现组件 index.htmlJavascript #选择器仅适用于根元素,不适用于角元素中的子元素,javascript,angular,typescript,angular8,Javascript,Angular,Typescript,Angular8,当我使用下面的id为根元素(应用程序组件)定义选择器时,我对选择器感到困惑,我能够呈现组件 index.html <body> <div id="root"></div> </body> app.component.html div class='my-text' >My Root Component</div> <div id='child'></div> 但如果我将选择器更改为,则可以渲
<body>
<div id="root"></div>
</body>
app.component.html
div class='my-text' >My Root Component</div>
<div id='child'></div>
但如果我将选择器更改为,则可以渲染子组件
selector=[id=child]
为什么用于父项的选择器定义在子项中失败
Angular version 8用于分析选择器的Angular编译器:
const _SELECTOR_REGEXP = new RegExp(
'(\\:not\\()|' + //":not("
'([-\\w]+)|' + // "tag"
'(?:\\.([-\\w]+))|' + // ".class"
// "-" should appear first in the regexp below as FF31 parses "[.-\w]" as a range
'(?:\\[([-.\\w*]+)(?:=([\"\']?)([^\\]\"\']*)\\5)?\\])|' + // "[name]", "[name=value]",
// "[name="value"]",
// "[name='value']"
'(\\))|' + // ")"
'(\\s*,\\s*)', // ","
'g');
如您所见,没有id选择器
此外,选择器#root
和#child
将与root
和child
元素匹配。因此,如果将
替换为
,则将呈现子组件
根选择器为什么工作
这是因为根组件被特殊处理,并通过使用以下代码作为动态组件引导:
componentFactory.create(Injector.NULL, [], selectorOrNode, ngModule);
^^^^^^^^^^^^^^
#root
如果我们提供了字符串,则在引擎盖下Angular使用document.querySelector(selectorNode)
查找专用元素
另一方面,只有当所有嵌套组件的选择器与模板中的元素匹配时,才会呈现它们。文档:不要谈论选择器
const _SELECTOR_REGEXP = new RegExp(
'(\\:not\\()|' + //":not("
'([-\\w]+)|' + // "tag"
'(?:\\.([-\\w]+))|' + // ".class"
// "-" should appear first in the regexp below as FF31 parses "[.-\w]" as a range
'(?:\\[([-.\\w*]+)(?:=([\"\']?)([^\\]\"\']*)\\5)?\\])|' + // "[name]", "[name=value]",
// "[name="value"]",
// "[name='value']"
'(\\))|' + // ")"
'(\\s*,\\s*)', // ","
'g');
componentFactory.create(Injector.NULL, [], selectorOrNode, ngModule);
^^^^^^^^^^^^^^
#root