首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >角2/输入/输出:@输入/@输出还是输入/输出?

角2/输入/输出:@输入/@输出还是输入/输出?
EN

Stack Overflow用户
提问于 2016-12-25 04:00:57
回答 2查看 14.3K关注 0票数 10

在进行关于Udemy的课程时,我们允许使用组件类中的@Input()装饰器传递组件的数据dy。

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

类似的问题上,有一个人回答:

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

并通过文档状态查看:

无论您使用输入/输出还是@Input/@Output,结果都是相同的,因此选择使用哪一个基本上是一个文体决定。

实际上,关于这一点的最有用的信息主要取决于你看的位置而相互矛盾。

内部 @Component

代码语言:javascript
复制
 @Component({
  selector: 'product-image',
  inputs: ['product'],
  template: `
  <img class="product-image" [src]="product.imageUrl">
})

class ProductImage {
  product: Product;
}

类中

代码语言:javascript
复制
@Component({
  selector: 'product-image',
  template: `
  <img class="product-image" [src]="product.imageUrl">
})

class ProductImage {
  @Input() product: Product;
}

我想知道的事情,

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

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-12-25 04:30:53

角2型导轨

根据官方的角2型导轨风格05-12

Do使用@Input@Output代替@Directive@Component装饰器的输入和输出属性。

好处是(从指南中):

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

我亲自使用过这种风格,并非常感谢它帮助保留了代码干的

票数 9
EN

Stack Overflow用户

发布于 2016-12-25 06:04:58

我知道你可以用装饰器做一件很酷的事情,但如果有可能的话,那就是把变量混在一起:

代码语言:javascript
复制
export class MyComponent {

 @Output('select') $onSelect = new EventEmitter<any>(); // this is aliased

 @Output() finish  = new EventEmitter<any>(); // not aliased

 sendUp(){
    this.$onSelect.emit('selected'); 

    this.finish.emit('done');
 }
}

然后从外面:

代码语言:javascript
复制
 <my-component (select)="doSomething($event)"></my-component>

另一种是设置默认值,您可以通过这两种方式设置默认值,但是装饰器看起来更方便,代码更少。

代码语言:javascript
复制
@Component({ 
  selector:'my-component'
})
export class MyComponent {
  @Input() id = 'default-id';     

  ngOnInit(){

    console.log('id is : ',this.id); // will output default-id if you don't pass anything when using the component
  }
}

因此,在这种情况下,如果使用者没有将id作为输入传递,则仍然有默认的id;

代码语言:javascript
复制
 <my-component></my-component>;

如果您想要使用输入数组执行此操作,您可以这样做:

代码语言:javascript
复制
@Component({ 
  selector:'my-component',
  inputs:['id']
})
export class MyComponent {
  private id = 'default-id';     

  ngOnInit(){

    console.log('id is : ',this.id); // will output default-id if you don't pass anything when using the component
  }
}

结果是相同的,但是如果您注意到,在这种情况下,您必须将id都放在输入数组中,并在类中定义它。

编辑:

显然,与outputs[]混叠也是可能的,如下所示:

代码语言:javascript
复制
@Component({
  selector: 'my-component',
  template: `
   <button (click)="sendUp()">Send up</button>
  `,
  outputs: ['$onSelect: select']
})
export class ChildComponent {
  $onSelect = new EventEmitter<any>(); // this is aliased

  sendUp() {
    this.$onSelect.emit('selected');
  }
}

但是,您必须在两个位置定义它,一个在数组中,另一个在类中,所以我仍然更喜欢装饰器。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41318575

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档