2016-12-25 79 views
5

在Udemy課程中,我們一直允許組件在組件類中使用@Input()裝飾器來傳遞數據dy。Angular 2/TypeScript:@ Input/@輸出或輸入/輸出?

在通過ngBook-2閱讀時,我發現使用@Component裝飾器中的input屬性還有另一種方法。

THIS類似的問題對SO,一個人回答說:

使用輸入的一個優點是類的用戶只需要看看傳遞給@Component裝飾的配置對象,以找到輸入(和輸出)屬性。

,並期待通過documentation狀態:

無論您使用的輸入/輸出或@輸入/輸出@的結果是相同的,所以在選擇使用哪一個在很大程度上是一種風格決定。

真的,這個最有用的信息取決於你往哪裏看主要是相互矛盾的。

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

事情我想知道

  • 什麼人會更多「最佳實踐」用法?
  • 什麼時候你會用另一個?
  • 有什麼不同嗎?
+0

還檢查http://stackoverflow.com/questions/40661325/why-is-input-decorator-preferred-over-inputs/40662020#answer-40661361 – yurzui

回答

6

角2風格指南

根據官方Angular 2 style guideSTYLE 05-12

使用@Input@Output,而不是@Directive的輸入和輸出性能和@Component裝飾

的好處是(從引導):

  • 這是比較容易和更具有可讀性,以確定其在類屬性是輸入或輸出。
  • 如果您需要重命名與@Input@Output關聯的屬性或事件名稱,則可以將其修改爲單個位置。
  • 附加到指令的元數據聲明更短,因此更具可讀性。
  • 將裝飾器放置在同一條線上使得代碼更短,並且仍然可以輕鬆地將該屬性標識爲輸入或輸出。

我個人使用這種風格,真的很感激它幫助保持代碼DRY

+0

是不是點(2)取決於你是什麼樣的IDE使用;如果它具有intellisense來識別裝飾器的屬性,爲什麼我們不能在一個地方更改'input:varname'? – ishandutta2007

1

其中之一,我知道你可以用裝飾做很酷的事情,但我不是否有可能用另一種方式,是別名變量:

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都在輸入數組並在類中定義它。

編輯:

與輸出[]顯然混淆也是可以的,像波紋管:

@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'); 
    } 
} 

但是你又必須在兩個地方定義它,對數組中,一個在類,所以我仍然更喜歡裝飾者。

+1

別名變量也可用於'outputs'。它看起來像'outputs:['$ onSelect:select']'https://plnkr.co/edit/QwTl8ZaDFfrusHcAoLkx?p=preview – yurzui

+0

@yurzui,好吧很酷,不知道這一點,我會更新answe: d – Milad