All files / track-changes track-changes.decorator.ts

100% Statements 9/9
100% Branches 7/7
100% Functions 3/3
100% Lines 9/9

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28                      2x 2x   2x 4x 4x 4x 1x     4x     2x      
import type { OnChanges, SimpleChanges } from '@angular/core';
 
/**
 * The track changes decorator.
 * @param key class member name
 * @param methodName change handler
 */
export function trackChanges<TargetClass = Record<string, unknown>, Value = unknown, Method = (value: Value) => void>(
  key: string,
  methodName: string,
) {
  return function (targetClass: TargetClass, functionName: 'ngOnChanges', descriptor: PropertyDescriptor) {
    const source: OnChanges[typeof functionName] = descriptor.value;
 
    descriptor.value = function (changes: SimpleChanges) {
      const currentValue: Value | null = changes[key]?.currentValue ?? null;
      const method: Method | undefined = (targetClass as Record<string, Method | undefined>)[methodName];
      if (typeof changes[key] !== 'undefined' && currentValue !== null && typeof method === 'function') {
        method.call(this, currentValue);
      }
 
      return source.call(this, changes);
    };
 
    return descriptor;
  };
}