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

前端 未结 2 578
我在风中等你
我在风中等你 2021-01-24 22:47
@Component({
   selector: \'my-cmp\',
   template: \'
Hello World!
\' }) // here component metadata export class MyComponent { }

相关标签:
2条回答
  • 2021-01-24 23:30

    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:

    0 讨论(0)
  • 2021-01-24 23:44

    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 { }

    0 讨论(0)
提交回复
热议问题