What does the @Component decorator do?

From official documents we know that

A component decoder allows you to mark a class as an Angular component and provide additional metadata that determines how the component should be processed, created, and used at runtime.

But I would like to go deeper and understand what the Component Decoder really does, besides providing additional metadata.

I plunged into the source code and found that all decorators are created using makeDecorator . And here I got lost. Where is the difference, for example, for Component and ngModule decorators? Do they do the same? Do not think so.

Like the answer, it would be nice to have a step-by-step description of what I should do to recreate the Decorator components without the makeDecorator function.

UPD : and, of course, I know how they work

+5
source share
1 answer

But I would like to go deeper and understand what the component decorator does, in addition to providing additional metadata.

Why should it be something else? He said that the argument passed to the @Component decorator function is the metadata of the component. So this is the primary responsibility for providing metadata.

The easiest way if you want to reproduce something like this is

  • Install reflect-metadata .

     npm install --save reflect-metadata 
  • Create a decorator function 1

     import 'reflect-metadata'; interface MyComponentMetadata { template?: string; selector?: string; } function MyComponent(metadata: MyComponentMetadata) { return function(ctor: Function) { // add metadata to constructor Reflect.defineMetadata('annotations', metadata, ctor); } } 
  • Use it

     @MyComponent({ selector: 'component', template: '<hello></hello>' }) class HelloComponent { } 
  • Now that you need to get the metadata, just do

     let metadata = Reflect.getMetadata('annotations', HelloComponent); 

The purpose of metadata is to provide information for Angular to know what to do with the class. Therefore, the decorator really should not be more than just a metadata provider. Angular decides what to do with the metadata, not the decorator function.


1 - see TypeScript decorator documentation

+8
source

Source: https://habr.com/ru/post/1260835/


All Articles