1

How do I use an Angular Input property as a parameter for a custom decorator?

some-component.html

<some-component [key]="'someString'"></some-component>

some.component.ts

export class SomeComponent {
  @Input()
  set key(value: string) {
    @SomeCustomDecorator(value)
  }
}
0

1 Answer 1

1

If you want for example a log decorator for all your input setters you can use the following decorator/function:

function Log(): any {
  return (target: any, propertyKey: string | symbol, propertyDescriptor: PropertyDescriptor) => {
    const key = Symbol();
    return {
      get() {
        return this[key]; 
      },
      set(newValue: any) {
        console.log('decorator: ', newValue);
        this[key] = newValue;
        if (propertyDescriptor) {
          propertyDescriptor.set(newValue);
        }
        return this;
      }
    }
  }
}

It can be used as the following:

@Input() @Log() foo;
@Input() @Log() set bar(v) {
  console.log('set bar: ', v);
}

The decorator will emit the following logs if you use the @Input() foo or @Input() bar:

decorator: "value"

Running stackblitz

Sign up to request clarification or add additional context in comments.

2 Comments

It's not really what i'm looknig for. The value of the Key input property (someString) should be a parameter for the decorator
In this example the value of the key input (someString) is available inside the decorator. The value is provided inside the decorator as newValue. Try to check the stackblitz. If you want to give your Decorator an custom param then declare the param in the first line. "function Log(param: any)"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.