在角2/4中,我们可以创建用于扩展父组件的自定义装饰器。在自定义装饰器中根据需要处理装饰器属性的实际覆盖。要获得父批注,我们使用:
let parentAnnotations = Reflect.getMetadata('annotations', parentTarget);
在升级到角5之后,这不再有效了。关于this的答案,我们可以使用:
用于获取父组件注释的target['__annotations__'][0]。
为了在角2/4中的当前组件中设置注释,我们使用了:
let metadata = new Component(annotation); Reflect.defineMetadata('annotations', [ metadata ], target);
如何在角5中设置当前组件注释?
发布于 2017-11-27 19:24:24
最后,我介绍了自定义装饰器(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 {
}注意:这还没有正式记录下来,而且在很多情况下也不起作用。我希望它能帮助其他人,但使用它是你自己的风险。
https://stackoverflow.com/questions/47504711
复制相似问题