Angular introduces module packaging concept
Angular introduces the concept of module packaging in a way similar to ES modules.
It basically means that the declareable types—components, instructions, and pipelines—can only be used by components declared within that module.
For example, if I try to use the following code in the App moduleApp
Use within the componentA
In the module a-comp
:
@Component({ selector: 'my-app', template: ` <h1>Hello {{name}}</h1> <a-comp></a-comp> ` }) export class AppComponent { }
Error message
Template parse errors: ‘a-comp’ is not a known element
This is because a-comp is not declared in the App module. If I want to use this component, I need to import the module that defines this component. The solution is as follows:
@NgModule({ imports: [..., AModule] }) export class AppModule { }
This is where the encapsulation comes into play: A module must declare it as available within other modules by adding a-comp to the exports array:
@NgModule({ ... declarations: [AComponent], exports: [AComponent] }) export class AModule { }
Most Angular beginners think that Providers also have encapsulations, and this idea is wrong. Providers declared in any non-latency loading module can be accessed anywhere within the application.
Modules hierarchy
aboutimported modules
The biggest confusion is that developers believe that these imported Modules maintain a hierarchy when the application runs, and assume that the modules imported from other modules become the parent modules of the imported module.
However, this is not the case. All modules are merged during the compilation phase. Therefore, there is no hierarchical relationship between the imported module and the imported module.
One of the required namespaces is defined as the default namespace. The control tag for this namespace does not require a prefix.
<View>
Tags are required, and in the example above, the core namespace is defined in the first line. Of course the developer can define any name. For example, to make the tag name shorter, you can also usec
Instead ofcore
.
The above is the detailed content of the common error analysis and understanding of Angular module packaging concept. For more information about Angular module packaging concept analysis, please pay attention to my other related articles!