在进行关于Udemy的课程时,我们允许使用组件类中的@Input()装饰器传递组件的数据dy。
在阅读ngBook-2时,我发现在input装饰器中使用@Component属性还有另一种方法。
在这类似的问题上,有一个人回答:
使用输入的一个优点是,类的用户只需查看传递给@Component装饰器的配置对象,就可以找到输入(和输出)属性。
并通过文档状态查看:
无论您使用输入/输出还是@Input/@Output,结果都是相同的,因此选择使用哪一个基本上是一个文体决定。
实际上,关于这一点的最有用的信息主要取决于你看的位置而相互矛盾。
内部 @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;
}我想知道的事情,
发布于 2016-12-25 04:30:53
发布于 2016-12-25 06:04:58
我知道你可以用装饰器做一件很酷的事情,但如果有可能的话,那就是把变量混在一起:
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');
}
}然后从外面:
<my-component (select)="doSomething($event)"></my-component>另一种是设置默认值,您可以通过这两种方式设置默认值,但是装饰器看起来更方便,代码更少。
@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;
<my-component></my-component>;如果您想要使用输入数组执行此操作,您可以这样做:
@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[]混叠也是可能的,如下所示:
@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');
}
}但是,您必须在两个位置定义它,一个在数组中,另一个在类中,所以我仍然更喜欢装饰器。
https://stackoverflow.com/questions/41318575
复制相似问题