ChristyPiffat
ChristyPiffat

Reputation: 379

Using Inheritance with AngularJS Components

I am using AngularJS components in anticipation of eventually moving to Angular2. I have a component (Component1) that is essentially a dropdown with a few specific inputs and outputs. I have another component (Component2) that is the exact same kind of dropdown, but has a dependency on the ng-model in Component1. Is there a way to use inheritance in Component2 so that I do not have a bunch of duplicate code?

I can see how to use inheritance in Angular2, so this seems to be the best approach. However, I can't find anything showing how to do this in Angular 1.5.

Component1 also requires a template, but it will be the same for both Component1 and Component2. Also, Component2 will require an additional input for the value from Component1, as well as some code in the $onChanges event when that additional input changes.

Thanks in advance!!

Upvotes: 2

Views: 1788

Answers (1)

hannad rehman
hannad rehman

Reputation: 4331

the best thing you can do is pass a model object to component 2 as bindings,

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

inside html

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

when change occures in component1. if your component depends on that change you need to use onchanges lifecycle hooks components.inside component2 controller

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}
}
}

Upvotes: 1

Related Questions