gpt4 book ai didi

angular - Angular 中的编译上下文是什么?

转载 作者:太空狗 更新时间:2023-10-29 17:23:26 25 4
gpt4 key购买 nike

在 Angular 文档中它说模块共享一个编译上下文。

NgModules provide a compilation context for their components. A root NgModule always has a root component that is created during bootstrap, but any NgModule can include any number of additional components, which can be loaded through the router or created through the template. The components that belong to an NgModule share a compilation context.

source

我只找到一种解释here .但我不太完全理解它或它的重要性。有人可以详细说明“编译上下文”的含义以及模块共享相同上下文的重要性吗?

最佳答案

Angular 文档说

The components that belong to an NgModule share a compilation context.

你听过这样的错误吗

WARNING: Template parse errors: 'A' is not a known element:

  1. If 'b-comp' is an Angular component, then verify that it is part of this module.

  2. If 'b-comp' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.

Can't bind to 'ngModel' since it isn't a known property of 'input'


编译上下文

您发现,链接中的解释正确描述了编译上下文的概念。

它是一组将被编译的东西(文件,组件)。这意味着上下文包含编译器无误编译所需的一切。

假设您编译 typescript 并使用 tsconfig.json 文件控制上下文,其中定义了 filesincludeexclude选项。这样, typescript 编译器将仅使用您提供的文件来查找您的 ts 代码之间的关系。

Angular 编译器

现在让我们回到 Angular 编译器。

Angular 编译器主要编译组件的模板。要编译模板,Angular 应该知道该模板中涉及的所有组件/指令。

假设我们有以下简单的组件:

@Component({
selector: 'a-comp`,
template: `
<h2>Hello, I'm a-comp</h2>
<div [scroll]="options">
<b-comp></b-comp>
</div>
`
})
export class ComponentA {}

这个组件是在一些 Angular 模块中定义的,例如:

@NgModule({
declarations: [
ComponentA
]
})
export class AModule {}

为了编译 ComponentA,angular 经历了以下阶段:

1) 找到它所属的NgModule。

ComponentA 是在 AModule 中声明的,所以这个模块成为它的编译上下文。

2) 查找在此模块范围内的所有其他指令。

Angular 正在搜索这个 NgModule 的所有可传递模块。 ( Angular 2 Use component from another module )

3) 通过将所有涉及的指令传递给编译器来运行编译

compileComponent(outputCtx, compMeta, ngModule, ngModule.transitiveModule.directives 
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

我们的 AModule 没有导入任何其他模块,也没有定义任何其他指令。这意味着 Angular 将无法编译 ComponentA 的模板(如果你当然没有使用 CUSTOM_ELEMENTS_SCHEMA):

<div [scroll]="options">
<b-comp></b-comp>
</div>

因为 Angular 编译器会寻找带有 scroll @Input 和 b-comp 的指令,但我们的范围 AModule 不包含此类指令。

换句话说,NgModule 没有为构建组件提供正确的编译上下文。 NgModule 是 Angular 编译器的一种配置,类似于 typescript 编译器的 tsconfig.json

同样,在 NgModule 中声明的组件和从导出它们的其他模块导入的组件共享相同的编译上下文(这里有更多信息 Angular 2 Use component from another module)

关于angular - Angular 中的编译上下文是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50940048/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com