Angular 2/TypeScript:@输入/@输出还是输入/输出? [英] Angular 2/TypeScript: @Input/@output or input/output?

查看:77
本文介绍了Angular 2/TypeScript:@输入/@输出还是输入/输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在进行有关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:

使用输入的一个优点是,该类的用户只需查看传递给@Component装饰器的配置对象,即可找到输入(和输出)属性.

One advantage of using inputs is that users of the class only need to look at the configuration object passed to the @Component decorator to find the input (and output) properties.

并仔细阅读文档指出:

无论使用输入/输出还是@ Input/@ Output的结果都是相同的,因此选择要使用的输入很大程度上是一个风格决定.

Whether you use inputs/outputs or @Input/@Output the result is the same so choosing which one to use is largely a stylistic decision.

真的,关于这方面最有用的信息主要取决于您的外观.

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样式指南

执行,请使用@Input@Output代替@Directive@Component装饰器的输入和输出属性

Do use @Input and @Output instead of the inputs and outputs properties of the @Directive and @Component decorators

好处是(根据指南):

  • 识别类中的哪些属性是输入或输出更容易且更具可读性.
  • 如果您需要重命名与@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:@输入/@输出还是输入/输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆