0

I was wondering whether it is possible to create a decorator for a property which checks if value is assigned to it or not yet.

I want to create a required Decorator on a property. Suppose I have a directive and some properties need to have a value which is given when the directive is used/called.

@Directive({...})
export class xyz
  @Input()
  @Required()
  get name() {...}
  set name(s: string) {...}
}

Somewhere other part of app.

<div xyz>....</div>

This should throw an error because name property is missing, and it is kind of required in directive class.

<div xyz [name]="'anyName'">....</div>

I have tried couple but can't...

export function Required() {
  return (target: {} | any, name: PropertyKey): any => {
    const descriptor = {
      get(this: any) {
        console.log(this);
        const propertyName = `__${String(name)}`;
        if (!this[propertyName]) {
          this[propertyName] = createId();
        }
        return this[propertyName];
      },
      enumerable: true,
      configurable: true,
    };
    Object.defineProperty(target, name, descriptor);
  };

But I can't acheive the goal.

I don't know how can I require a property via decorator. I know there is an other way using selector but I was wondering if this can be done by a decorator.

Thanks

Edit: At runtime is it possible to use the decorator?

Phoenix404
  • 898
  • 1
  • 14
  • 29

1 Answers1

1

Something like this ?

https://stackblitz.com/edit/angular-ivy-ufdinz?file=src%2Fapp%2Frequired.ts,src%2Fapp%2Fhello.component.ts

enter image description here

export function Required() {
  return (target: any, key: string) => {
    if (!target[key]) throw new Error(`Property ${key} is required on class ${target.constructor.name}`);
  };
}

Be aware that decorators are run when your class is being instanciated : this means that if you @Input sets the value to null, it won't work.

  • is it possible to triggerer decotrators when class is initiated? – Phoenix404 May 23 '22 at 14:48
  • Like, I have an example here: https://stackblitz.com/edit/angular-ivy-zpswab and doesn't work required. – Phoenix404 May 23 '22 at 14:48
  • The decorators are triggered when the class is instanciated, that's the only moment when they are. Maybe I misread your question ? –  May 23 '22 at 14:48