#selector 仅适用于根元素,不适用于 angular 中的子元素
#selector is working only for root element not for child in angular
当我使用如下 id 为根元素(应用程序组件)定义选择器时,我对选择器感到困惑我能够呈现组件
index.html
<body>
<div id="root"></div>
</body>
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: '#root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'helloworld';
}
app.component.html
div class='my-text' >My Root Component</div>
<div id='child'></div>
我能够呈现父组件,但是如果我在子选择器中遵循相同的定义规则,我将无法呈现子组件
@Component({
selector: '#child',
templateUrl: './child1.component.html',
styleUrls: ['./child1.component.scss']
})
但是如果我将选择器更改为
selector=[id=child]
为什么适用于父项的选择器定义在子项中失败?
Angular 版本 8
Angular编译器uses the following regexp解析选择器:
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
元素匹配。因此,如果您将 <div id='child'></div>
替换为 <child></child>
,那么子组件将被渲染。
为什么根选择器有效?
这是因为根组件被特殊处理,并使用以下代码将其引导为动态组件:
componentFactory.create(Injector.NULL, [], selectorOrNode, ngModule);
^^^^^^^^^^^^^^
#root
如果我们提供了字符串,Angular 使用 document.querySelector(selectorOrNode)
查找专用元素。
另一方面,所有嵌套组件只有在选择器与模板中的元素匹配时才会呈现。
当我使用如下 id 为根元素(应用程序组件)定义选择器时,我对选择器感到困惑我能够呈现组件
index.html
<body>
<div id="root"></div>
</body>
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: '#root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'helloworld';
}
app.component.html
div class='my-text' >My Root Component</div>
<div id='child'></div>
我能够呈现父组件,但是如果我在子选择器中遵循相同的定义规则,我将无法呈现子组件
@Component({
selector: '#child',
templateUrl: './child1.component.html',
styleUrls: ['./child1.component.scss']
})
但是如果我将选择器更改为
selector=[id=child]
为什么适用于父项的选择器定义在子项中失败?
Angular 版本 8
Angular编译器uses the following regexp解析选择器:
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
元素匹配。因此,如果您将 <div id='child'></div>
替换为 <child></child>
,那么子组件将被渲染。
为什么根选择器有效?
这是因为根组件被特殊处理,并使用以下代码将其引导为动态组件:
componentFactory.create(Injector.NULL, [], selectorOrNode, ngModule);
^^^^^^^^^^^^^^
#root
如果我们提供了字符串,Angular 使用 document.querySelector(selectorOrNode)
查找专用元素。
另一方面,所有嵌套组件只有在选择器与模板中的元素匹配时才会呈现。