我尝试扩展Material 2 sidenav组件,以便在关闭之前添加所需的确认。经过大量搜索后,我发现了一种扩展装饰器的潜在方法,因此我不必复制/重写扩展组件的模板和样式:
Extending component decorator with base class decorator
不幸的是,我收到了错误:
Cannot read property '0' of undefined
就行:
const parentAnnotation = parentAnnotations[0];
当我尝试使用该解决方案时。 我究竟做错了什么?
继承我的代码:
import { MdSidenav } from '@angular/material';
import { Component, OnInit } from '@angular/core';
import 'zone.js';
import 'reflect-metadata';
function isPresent(obj: any): boolean {
return obj !== undefined && obj !== null;
}
export function CustomComponent(annotation: any) {
return function (target: Function) {
const parentTarget = Object.getPrototypeOf(target.prototype).constructor;
console.log(Reflect.getMetadataKeys(parentTarget));
const parentAnnotations = Reflect.getMetadata('annotations', parentTarget);
const 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];
}
}
});
const metadata = new Component(annotation);
Reflect.defineMetadata('annotations', [ metadata ], target);
};
}
@CustomComponent({
selector: 'xw-sidenav'
})
export class XwSidenavComponent extends MdSidenav {
}