Angular 4 - 模板继承

Tre*_*tor 8 angular

我有以下子组件和它的继承父组件:

@Component({
   template: `<p>child</p>`
})
export class EditChildComponent extends EditViewComponent{
   constructor(){
     super();
   }
}



@Component({
   template: `<p>parent</p>`
})
export class EditViewComponent{
   constructor(){
   }
}
Run Code Online (Sandbox Code Playgroud)

现在有没有办法将EditViewComponent的模板放在ChildComponents模板中,就像在嵌套组件中使用ng-content一样?我如何得到以下结果:

<p>parent</p>
<p>child</p>
Run Code Online (Sandbox Code Playgroud)

小智 -1

看这篇文章: Angular 2,装饰器和类继承

示例: plnkr.co

import {bootstrap} from 'angular2/platform/browser';
import {
  Component, 
  ElementRef,
  ComponentMetadata
} from 'angular2/core';
import { isPresent } from 'angular2/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 ComponentMetadata(annotation);

    Reflect.defineMetadata('annotations', [ metadata ], target);
  }
}

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

}

@CustomComponent({
  // override property annotation
  //selector: 'sub',
  // ANSWER: it's not possible like that but you could have a function here. Something like:
  template: (template) => { return template + 'add html to temlate in child'}
  selector: (parentSelector) => { return parentSelector + 'sub'}
})
export class SubComponent extends AbstractComponent {
  constructor() {
    //console.log(super);
  }
}

@Component({
  selector: 'app',
  // CHECK: change view for teste components
  template: `
    <div>
      <div><sub>seletor sub not work</sub></div>
      <div><master>selector master not work</master></div>
      <div><mastersub>selector mastersub not work</mastersub></div>
    </div>
  `,
  directives [ SubComponent ]
})
export class App {

  constructor(private elementRef:ElementRef) {
  }

}

bootstrap(App).catch(err => console.error(err));
Run Code Online (Sandbox Code Playgroud)

  • 标题指出 Angular 4 (3认同)