angular 2 inheriting from a base-component

后端 未结 1 1000
萌比男神i
萌比男神i 2021-02-09 02:17

My question is an extension to another question here on so: Angular2 and class inheritance support

And here is my plunckr: http://plnkr.co/edit/ihdAJuUcyOj5Ze93BwIQ?p=pr

1条回答
  •  故里飘歌
    2021-02-09 02:35

    It's not possible the way you do since Angular2 will only have a look at the annotations for the current component but not on the component above.

    That being said, you can work at the level of annotations to make inherit annotations of the parent component:

    export function Inherit(annotation: any) {
      return function (target: Function) {
        var parentTarget = Object.getPrototypeOf(target.prototype).constructor;
        var parentAnnotations = Reflect.getMetadata('design:paramtypes', parentTarget);
    
        Reflect.defineMetadata('design:paramtypes', parentAnnotations, target);
      }
    }
    

    And use it like this:

    @Inherit()
    @Component({
      (...)
    })
    export class ChildComponent1 extends BaseComponent {
      constructor() {
        super(arguments);
      }
    }
    

    See this question for more details:

    • Angular2 use imported libs from base class

    The following article could interest you to understand what happens under the hood:

    • https://medium.com/@ttemplier/angular2-decorators-and-class-inheritance-905921dbd1b7#.mrhhol5p7

    You also need to be aware that working on annotations directly has drawbacks especially regarding offline compilation and for component introspection in IDEs.

    0 讨论(0)
提交回复
热议问题