简体   繁体   中英

What happens when there are two classes, one decorator/ one class two decorators in a file in Angular 2?

@Component({
   selector: 'my-cmp',
   template: '<div>Hello World!</div>'
}) // here component metadata

export class MyComponent {

}

So, the above is my actual component file. If I have another class

@Component({
   selector: 'my-cmp',
   template: '<div>Hello World!</div>'
}) // here component metadata

export class MyComponent {

}

export class MyAnotherComponent {

}

and

@Component({
   selector: 'my-cmp',
   template: '<div>Hello World!</div>'
}) // here component metadata
@Component({
   selector: 'my-cmpnt',
   template: '<div>Hello Something!</div>'
}) // here component metadata

export class MyComponent {

}

Now, Do I get any error? What happens?

Two classes and one decorator

The @Component decorator is applied to the class that immediately follows the decorator. So in your case it's applied to MyComponent . Now, it also matters which class your specify in a module declarations. If you specify MyComponent - everything should be fine. If you specify MyAnotherComponent - you will get an error:

Unexpected value 'MyAnotherComponent' declared by the module 'AppModule'. Please add a @Pipe/@Directive/@Component annotation.

because Angular will complain that this class is not an instance of a component because the decorator wasn't applied to it.

You can read more about @Component decorator and how it works here .

Two decorators and one class

In short, only the first decorator is used.

If you use two decorators on the same class, both will be applied to the class and store metadata on that class in reverse order , so that the first decorator properties stored in the last index. When the compiler resolves metadata it takes the last metadata properties using the findLast function, which essentially picks the first decorator properties in your file.

So in your case only the my-cmp will be supported. If you use in your html my-cmpnt tag, you will get an error:

Template parse errors: 'my-cmpnt' is not a known element:

You can't have a component with two component decorators (@Component). You need to create two different classes for this:

 @Component({ selector: 'app', template: `<h1>Title Here</h1>` }) export class AppComponent { } @Component({ selector: 'appTwo', template: `<h1>Another Title Here</h1>` }) export class AppComponent1 { } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM