Property Decorators

Property decorators work with properties of classes.

  1. function Override(label: string) {
  2. return function (target: any, key: string) {
  3. Object.defineProperty(target, key, {
  4. configurable: false,
  5. get: () => label
  6. });
  7. }
  8. }
  9. class Test {
  10. @Override('test') // invokes Override, which returns the decorator
  11. name: string = 'pat';
  12. }
  13. let t = new Test();
  14. console.log(t.name); // 'test'

The above example must be compiled with both the —experimentalDecoratorsand —emitDecoratorMetadata flags.

In this case the decorated property is replaced by the label passed to thedecorator. It's important to note that property values cannot bedirectly manipulated by the decorator; instead an accessor is used.

Here's a classic property example that uses a plain decorator

  1. function ReadOnly(target: any, key: string) {
  2. Object.defineProperty(target, key, { writable: false });
  3. }
  4. class Test {
  5. @ReadOnly // notice there are no `()`
  6. name: string;
  7. }
  8. const t = new Test();
  9. t.name = 'jan';
  10. console.log(t.name); // 'undefined'

In this case the name property is not writable, and remains undefined.

原文: https://angular-2-training-book.rangle.io/handout/features/property_decorators.html