2016-07-26 27 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} 
} 
}