Angular 2 / TypeScript:@ Input / @输出或输入/输出?

前端之家收集整理的这篇文章主要介绍了Angular 2 / TypeScript:@ Input / @输出或输入/输出?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在Udemy上做一门课程的时候,我们一直允许组件使用组件类中的@Input()装饰器传递数据.

在通过ngBook-2阅读时,我发现在@Component装饰器中使用input属性还有另一种方法.

关于SO的THIS个类似的问题,一个人回答:

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.

并通过documentation状态看:

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

实际上,最有用的信息主要是相互矛盾的,具体取决于你的外观.

在@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;
}

我想知道的事情

>更多的是“最佳实践”用法
>你什么时候用一个而不是另一个?
>有什么不同吗?

角度2风格指南

根据官方Angular 2 style guide,STYLE 05-12

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

好处是(来自指南):

>识别类中的哪些属性是输入或输出更容易,更易读.
>如果您需要重命名与@Input或@Output关联的属性或事件名称,则可以将其修改为单个位置.
>附加到指令的元数据声明更短,因此更具可读性.
>将装饰器放在同一行上可以缩短代码,并且仍然可以轻松地将属性标识为输入或输出.

我个人使用这种风格,非常感谢它帮助保持代码DRY.

原文链接:https://www.f2er.com/angularjs/240543.html

猜你在找的Angularjs相关文章