问题描述
@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 {
}
和
@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?
推荐答案
两个类和一个装饰器
@Component
装饰器应用于紧跟在装饰器之后的类.因此,在您的情况下,它应用于 MyComponent
.现在,您在模块声明中指定哪个类也很重要.如果您指定 MyComponent
- 一切都应该没问题.如果你指定 MyAnotherComponent
- 你会得到一个错误:
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:
模块AppModule"声明的意外值MyAnotherComponent".请添加@Pipe/@Directive/@Component 注解.
因为 Angular 会抱怨这个类不是组件的实例,因为装饰器没有应用于它.
because Angular will complain that this class is not an instance of a component because the decorator wasn't applied to it.
您可以阅读有关 @Component
装饰器及其工作原理的更多信息 此处.
You can read more about @Component
decorator and how it works here.
简而言之,只使用第一个装饰器.
In short, only the first decorator is used.
如果您在同一个类上使用两个装饰器,则两者都将应用于该类并以相反的顺序在该类上存储元数据,以便第一个装饰器属性存储在最后一个索引中.当编译器解析元数据时,它使用 findLast 函数,它本质上选择文件中的第一个装饰器属性.
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.
因此,在您的情况下,仅支持 my-cmp
.如果你在你的 html my-cmpnt
标签中使用,你会得到一个错误:
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:
模板解析错误:my-cmpnt"不是已知元素:
这篇关于当 Angular 2 的文件中有两个类,一个装饰器/一个类两个装饰器时会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!