最后我想到了自定义装饰器的实现(extendedcomponent.decorator.ts):
import { Component } from '@angular/core';
export function ExtendedComponent(extendedConfig: Component = {}) {
return function (target: Function) {
const ANNOTATIONS = '__annotations__';
const PARAMETERS = '__paramaters__';
const PROP_METADATA = '__prop__metadata__';
const annotations = target[ANNOTATIONS] || [];
const parameters = target[PARAMETERS] || [];
const propMetadata = target[PROP_METADATA] || [];
if (annotations.length > 0) {
const parentAnnotations = Object.assign({}, annotations[0]);
Object.keys(parentAnnotations).forEach(key => {
if (parentAnnotations.hasOwnProperty(key)) {
if (!extendedConfig.hasOwnProperty(key)) {
extendedConfig[key] = parentAnnotations[key];
annotations[0][key] = '';
} else {
if (extendedConfig[key] === parentAnnotations[key]){
annotations[0][key] = '';
}
}
}
});
}
return Component(extendedConfig)(target);
};
}
用法示例:
首先像往常一样实现父组件(myparent.component.ts):
import { Component, Output, EventEmitter, Input } from '@angular/core';
@Component({
selector: 'my-component',
templateUrl: 'my.component.html'
})
export class MyParentComponent implements OnInit {
@Input() someInput: Array<any>;
@Output() onChange: EventEmitter<any> = new EventEmitter();
constructor(
public formatting: FormattingService
) {
}
ngOnInit() {
}
onClick() {
this.onChange.emit();
}
}
之后实现继承父组件的子组件:
import { Component, OnInit } from '@angular/core';
import { ExtendedComponent } from './extendedcomponent.decorator';
import { MyParentComponent } from './myparent.component';
@ExtendedComponent ({
templateUrl: 'mychild.component.html'
})
export class MyChildComponent extends MyParentComponent {
}
注意:这没有正式记录,并且在许多情况下可能不起作用。我希望它对其他人有帮助,但使用它的风险由您自己承担。