将@Input()
装饰器应用于我的组件属性,然后与我的自定义装饰器链接。
我似乎无法读取/设置任何公共属性 - 即使它们绑定正确。
例如
@Input()
@Language('global.pw.current')
public existingPasswordLabel: string;
然后在我的语言装饰者
export function Language(keyId: string): PropertyDecorator {
return (target: any, key: string) => {
setTimeout(()=>{
console.log(target[key]); //This is never set but is on screen
// in fact none of my public component properties are on the target
},1000); //Plenty of delay to make sure binding has happened
};
}
此时如何读取/写入我的组件属性。
答案 0 :(得分:2)
target
对象不是您的类的实例,它是类本身,并且由于您尝试设置的属性位于类的实例上,target[key]
将永远不会设置为任何东西(它本质上是Class[key]
)
您可以尝试将该字段覆盖为属性,以便在获取/设置属性时有权访问
export function Language(keyId: string): PropertyDecorator & MethodDecorator {
return (target: any, key: string, desc?: PropertyDescriptor) => {
desc = desc || {
get: function () {
return this["_" + key];
},
configurable: true,
enumerable: true
};
let baseSetter = desc.set || function (value) {
this["_" + key] = value;
};
desc.set = function (value) {
console.log(`Value of ${key} is ${value} with ${keyId}`);
baseSetter.call(this, value);
};
// We return the property descriptor which will be used to define the property using Object.defineProperty in the __decorate helper
return desc;
};
}
class ChildComponent {
@Language('global.pw.current')
@Input()
public existingPasswordLabel: string;
// Works with properties as well
private _title: string;
@Language('global.title')
@Input()
public get title(): string {
return this._title;
}
public set title(value: string) {
this._title = value;
}
}
注意:我没有添加@Input
装饰器进行测试,但它应该有效。
编辑使用@Input
装饰器进行测试,一切都按预期工作。我还更新了代码以使用字段和属性。