【问题标题】:#selector is working only for root element not for child in angular#selector 仅适用于根元素,不适用于 Angular 中的子元素
【发布时间】:2019-07-07 11:29:08
【问题描述】:

当我使用 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 版

【问题讨论】:

标签: javascript angular typescript angular8


【解决方案1】:

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 元素。因此,如果您将&lt;div id='child'&gt;&lt;/div&gt; 替换为&lt;child&gt;&lt;/child&gt;,则子组件将被渲染。

为什么根选择器有效?

这是因为根组件被特殊对待并使用以下代码作为动态组件引导:

componentFactory.create(Injector.NULL, [], selectorOrNode, ngModule);
                                           ^^^^^^^^^^^^^^
                                             #root

如果我们提供了字符串,Angular 会使用document.querySelector(selectorOrNode) 来查找专用元素。

另一方面,所有嵌套组件只有在它们的选择器与模板中的元素匹配时才会被渲染。

【讨论】:

    猜你喜欢
    • 2017-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 2021-06-10
    相关资源
    最近更新 更多