Decorator Pattern

In Angular, the Decorator Pattern is commonly used to add behavior or modify the functionality of classes or components without altering their code directly.

Angular itself leverages decorators extensively for various purposes such as defining components, services, directives, etc.

Let's say you have a simple Angular component that displays some information:

import { Component } from '@angular/core';

@Component({
  selector: 'app-info',
  template: `<div>{{info}}</div>`
})
export class InfoComponent {
  info: string = 'This is some information.';
}

Now, let's imagine you want to add some additional functionality to this component, such as logging each time the info property is accessed or modified.

You can achieve this using a decorator.

Here's how you can create a decorator to log property access:

function logPropertyAccess(target: any, key: string) {
  let value = target[key];

  Object.defineProperty(target, key, {
    get: function() {
      console.log(`Getting value of ${key}: ${value}`);
      return value;
    },
    set: function(newValue) {
      console.log(`Setting value of ${key} to ${newValue}`);
      value = newValue;
    }
  });
}

Now, you can apply this decorator to the info property of the InfoComponent:

import { Component } from '@angular/core';

function logPropertyAccess(target: any, key: string) {
  let value = target[key];

  Object.defineProperty(target, key, {
    get: function() {
      console.log(`Getting value of ${key}: ${value}`);
      return value;
    },
    set: function(newValue) {
      console.log(`Setting value of ${key} to ${newValue}`);
      value = newValue;
    }
  });
}

@Component({
  selector: 'app-info',
  template: `<div>{{info}}</div>`
})
export class InfoComponent {
  @logPropertyAccess
  info: string = 'This is some information.';
}

Now, whenever the info property of InfoComponent is accessed or modified, it will log the corresponding action to the console.

This allows you to add behavior to the component without modifying its original code directly, which is the essence of the Decorator Pattern.

Last updated