2017-09-19 26 views
0

我有幾個組件都做同樣的事情:可能在組件之間共享邏輯?

  • 顯示的形式(形式雖然各不相同,所以HTML不同,每個)
  • 捕獲形式
  • 驗證和使用發送形式REST API

我期望在組件間分享某些內容。例如,形式都具有RadioButtons具有以下值的列表:

@Input() radioList: Object[] = [ 
    { label: 'Unsatisfactory', value: 1 }, 
    { label: 'Needs Improvement', value: 2 }, 
    { label: 'Meets Expectations', value: 3 }, 
    { label: 'Exceeds Expectations', value: 4 }, 
    { label: 'Outstanding', value: 5 } 
    ]; 

有沒有辦法像這樣分享的東西,所以如果我想編輯RadioList,我沒有做的四項次?

回答

1

擴展類?

//property and property-level annotations (@Input) will be picked up by ancestors 
export abstract class RadioListAwareComponent{ 
    @Input() radioList: Object[] = [ 
     { label: 'Unsatisfactory', value: 1 }, 
     { label: 'Needs Improvement', value: 2 }, 
     { label: 'Meets Expectations', value: 3 }, 
     { label: 'Exceeds Expectations', value: 4 }, 
     { label: 'Outstanding', value: 5 } 
    ]; 
} 

@Component({ 
    template: `<div>Comp1</div>` 
}) 
export class RadioListImplComponentONE extends RadioListAwareComponent{} 

@Component({ 
    template: `<div>Comp2</div>` 
}) 
export class RadioListImplComponentTWO extends RadioListAwareComponent{} 
+0

所以我會有一個組件'BaseImpl',它不會有HTML。然後我會創建4個其他組件並擴展'BaseImpl'並使用不同的HTML? – Nxt3

+0

已更新的答案。不需要單獨的'BaseImpl'。抽象類已經有屬性和註解。任何擴展RadioListAwareComponent的類都可以訪問radioList,並且該屬性可以用作輸入。請注意,類級別註釋('@ Component')不能在angular2中擴展(即不能共享相同的內聯模板)。 –

+0

所以我會做一個類(不是'@ Component'),然後創建4個組件來擴展這個類? – Nxt3