繁体   English   中英

在Angular 2的文件中有两个类(一个装饰器/一个类两个装饰器)会发生什么?

[英]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 {

}

因此,以上是我的实际组件文件。 如果我再上课

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

export class MyComponent {

}

export class MyAnotherComponent {

}

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

}

现在,我有任何错误吗? 怎么了?

两堂一装饰

@Component装饰器应用于紧随装饰器的类。 因此,在您的情况下,它将应用于MyComponent 现在,在模块声明中指定哪个类也很重要。 如果指定MyComponent一切都应该没问题。 如果指定MyAnotherComponent您将收到一个错误:

模块“ AppModule”声明了异常值“ MyAnotherComponent”。 请添加@ Pipe / @ Directive / @ Component批注。

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

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

两名装饰工和一名班级

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

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

因此,在您的情况下,仅支持my-cmp 如果在html my-cmpnt标记中使用,则会收到错误消息:

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

一个组件不能带有两个组件装饰器(@Component)。 您需要为此创建两个不同的类:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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