How to extend / inherit components?

后端 未结 12 818
萌比男神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:13

    Alternative Solution:

    This answer of Thierry Templier is an alternative way to get around the problem.

    After some questions with Thierry Templier, I came to the following working example that meets my expectations as an alternative to inheritance limitation mentioned in this question:

    1 - Create custom decorator:

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

    2 - Base Component with @Component decorator:

    @Component({
      // create seletor base for test override property
      selector: 'master',
      template: `
        
    Test
    ` }) export class AbstractComponent { }

    3 - Sub component with @CustomComponent decorator:

    @CustomComponent({
      // override property annotation
      //selector: 'sub',
      selector: (parentSelector) => { return parentSelector + 'sub'}
    })
    export class SubComponent extends AbstractComponent {
      constructor() {
      }
    }
    

    Plunkr with complete example.

提交回复
热议问题