问题描述
在进行有关Udemy的课程时,我们一直允许使用组件类中的@Input()
装饰器将组件传递给数据dy.
While doing a course on Udemy we have been allowing components to be passed data dy using the @Input()
decorator in the component class.
在阅读ngBook-2时,我发现有另一种方法是在@Component
装饰器中使用input
属性.
While reading through ngBook-2 I have found that there is another approach by using the input
property inside an @Component
decorator.
THIS 类似的问题在SO上,一个人回答:
THIS similar question on SO, One person answered:
并仔细阅读文档指出:
真的,关于这方面最有用的信息主要取决于您的外观.
Really, the most useful information about this is mostly conflicting depending on where you look.
内部@Component
@Component({
selector: 'product-image',
inputs: ['product'],
template: `
<img class="product-image" [src]="product.imageUrl">
})
class ProductImage {
product: Product;
}
内部课程
@Component({
selector: 'product-image',
template: `
<img class="product-image" [src]="product.imageUrl">
})
class ProductImage {
@Input() product: Product;
}
我想知道的事情
- 哪种最佳实践"用法更合适?
- 您何时会使用另一个?
- 有什么区别吗?
推荐答案
Angular 2样式指南
根据官方 Angular 2样式指南,样式05-12 说
好处是(根据指南):
- 识别类中的哪些属性是输入或输出更容易且更具可读性.
- 如果您需要重命名与
@Input
或@Output
关联的属性或事件名称,则可以在单个位置进行修改. - 该指令所附的元数据声明更短,因此更具可读性.
- 将装饰器放在同一行上可以缩短代码长度,并且仍然可以轻松地将该属性标识为输入或输出.
- It is easier and more readable to identify which properties in a class are inputs or outputs.
- If you ever need to rename the property or event name associated with
@Input
or@Output
, you can modify it a single place. - The metadata declaration attached to the directive is shorter and thus more readable.
- Placing the decorator on the same line makes for shorter code and still easily identifies the property as an input or output.
我亲自使用了这种样式,并且非常感谢它有助于使代码保持 DRY .
I've personally used this style and really appreciate it helping keep the code DRY.
这篇关于Angular 2/TypeScript:@输入/@输出还是输入/输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!