2016-07-26 109 views
2

我正在使用AngularJS組件來預期最終轉移到Angular2。我有一個組件(Component1),它基本上是一個具有幾個特定輸入和輸出的下拉菜單。我有另一個組件(Component2),它是完全相同類型的下拉列表,但依賴於Component1中的ng模型。有沒有辦法在Component2中使用繼承,以便我沒有一堆重複的代碼?在AngularJS組件中使用繼承

我可以看到如何在Angular2中使用繼承,所以這似乎是最好的方法。但是,我無法在Angular 1.5中找到任何顯示如何執行此操作的內容。

Component1也需要一個模板,但它對於Component1和Component2都是一樣的。此外,Component2將需要額外的輸入來處理來自Component1的值,以及在附加輸入發生更改時$ onChanges事件中的一些代碼。

在此先感謝!

回答

1

你能做的最好的事情是通過一個模型對象組件2爲綁定,

app..component('component2', { 
    bindings: { 
    modelObject: '<' 
    }, 
    controller: function() { 
    //do stuff 
    } 
}); 

裏面的html

<component2 model-object="$ctrl.modalObject"></component2> 

時變化COMPONENT1 occures。如果您的組件取決於該變化 您需要使用onchanges生命週期掛鉤components.inside組件2控制器

this.$onChanges=function(data){ 
    //this data has all changed values.. 
    // you can also use isFirstChange() to determine if it was the first or not. 
    if(data.hasOwnProperty('modalObject'){ 
    if(!data.modalObject.isFirstChange()){//means its not the initialization} 
} 
}