当 Angular 2 中的一个文件中有两个类、一个装饰器/一类两个装饰器时会发生什么?

Mr_*_*ect 1 angular2-template angular

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

export class MyComponent {

}
Run Code Online (Sandbox Code Playgroud)

所以,上面是我实际的组件文件。如果我还有别的课

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

export class MyComponent {

}

export class MyAnotherComponent {

}
Run Code Online (Sandbox Code Playgroud)

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

}
Run Code Online (Sandbox Code Playgroud)

现在,我有任何错误吗?会发生什么?

Max*_*kyi 5

两个类和一个装饰器

\n\n

装饰@Component器应用于紧随装饰器之后的类。所以在你的情况下它适用于MyComponent. 现在,在模块声明中指定哪个类也很重要。如果您指定MyComponent- 一切都应该没问题。如果你指定MyAnotherComponent- 你会得到一个错误:

\n\n
\n

模块 \xe2\x80\x98AppModule\xe2\x80\x99 声明的意外值 \xe2\x80\x98MyAnotherComponent\xe2\x80\x99。\n 请添加 @Pipe/@Directive/@Component 注释。

\n
\n\n

因为 Angular 会抱怨这个类不是组件的实例,因为装饰器没有应用于它。

\n\n

您可以在此处@Component阅读有关装饰器及其工作原理的更多信息的更多信息。

\n\n

两个装饰器和一个类

\n\n

简而言之,只使用了第一个装饰器。

\n\n

如果在同一个类上使用两个装饰器,则两者都将应用于该类并以相反的顺序存储该类上的元数据,以便第一个装饰器属性存储在最后一个索引中。当编译器解析元数据时,它使用findLast获取最后的元数据属性函数获取最后一个元数据属性,该函数实际上会选择文件中的第一个装饰器属性。

\n\n

所以在你的情况下,只有my-cmpwill 受到支持。如果你在 htmlmy-cmpnt标签中使用,你会得到一个错误:

\n\n
\n

模板解析错误:\'my-cmpnt\' 不是已知元素:

\n
\n