ngx-decorate
Version:
Useful decorators for Angular 2 and above
48 lines • 1.9 kB
JavaScript
import { ensureSymbol } from './lib/ensureSymbol';
import { HookManager } from './lib/HookManager';
import { _setProp } from './lib/symbols';
import { setProp } from './processors/setProp';
/**
* Mark the property as a subject setter. When written to, it will call .next(value) on the subject.
* The decorator's <b>default</b> config option only works on items that make use of the OnInit hook,
* i.e. it will <b>not</b> work for services and pipes.
*
* Because the <b>default</b> config option utilises the OnInit hook, it should not be used on
* properties that are component inputs as the input would get overridden during the hook.
*
* @param subjectPropName Name of the property at which the subject resides
* @param conf Optional configuration
*/
export function SubjectSetter(subjectPropName, conf = {}) {
return (target, prop) => {
const symbolValue = Symbol(`subjectSetter:${prop.toString()}`);
const defaultDescriptor = {
configurable: true,
enumerable: true
};
const defaultValue = conf.default || target[prop];
if (defaultValue) {
ensureSymbol(target, _setProp, [])
.push({ prop, value: defaultValue });
HookManager.for(target).add(2 /* POST_INIT */, setProp);
}
Object.defineProperties(target, {
[symbolValue]: {
configurable: false,
enumerable: false,
value: defaultValue,
writable: true
},
[prop]: Object.assign(defaultDescriptor, conf.desc || {}, {
get() {
return this[symbolValue];
},
set(v) {
this[symbolValue] = v;
this[subjectPropName].next(v);
}
})
});
};
}
//# sourceMappingURL=SubjectSetter.js.map