How to extend / inherit components?

后端 未结 12 812
萌比男神i
萌比男神i 2020-12-02 04:11

I would like to create extensions for some components already deployed in Angular 2, without having to rewrite them almost completely, as the base component could undergo ch

12条回答
  •  离开以前
    2020-12-02 05:03

    If anyone is looking for an updated solution, Fernando's answer is pretty much perfect. Except that ComponentMetadata has been deprecated. Using Component instead worked for me.

    The full Custom Decorator CustomDecorator.ts file looks like this:

    import 'zone.js';
    import 'reflect-metadata';
    import { Component } from '@angular/core';
    import { isPresent } from "@angular/platform-browser/src/facade/lang";
    
    export function CustomComponent(annotation: any) {
      return function (target: Function) {
        var parentTarget = Object.getPrototypeOf(target.prototype).constructor;
        var parentAnnotations = Reflect.getMetadata('annotations', parentTarget);
    
        var parentAnnotation = parentAnnotations[0];
        Object.keys(parentAnnotation).forEach(key => {
          if (isPresent(parentAnnotation[key])) {
            // verify is annotation typeof function
            if(typeof annotation[key] === 'function'){
              annotation[key] = annotation[key].call(this, parentAnnotation[key]);
            }else if(
              // force override in annotation base
              !isPresent(annotation[key])
            ){
              annotation[key] = parentAnnotation[key];
            }
          }
        });
    
        var metadata = new Component(annotation);
    
        Reflect.defineMetadata('annotations', [ metadata ], target);
      }
    }
    

    Then import it in to your new component sub-component.component.ts file and use @CustomComponent instead of @Component like this:

    import { CustomComponent } from './CustomDecorator';
    import { AbstractComponent } from 'path/to/file';
    
    ...
    
    @CustomComponent({
      selector: 'subcomponent'
    })
    export class SubComponent extends AbstractComponent {
    
      constructor() {
        super();
      }
    
      // Add new logic here!
    }
    

提交回复
热议问题