imnew123
imnew123

Reputation: 103

Using a decorator inside an Angular input decorator

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)
  }
}

Upvotes: 1

Views: 805

Answers (1)

Jonathan Stellwag
Jonathan Stellwag

Reputation: 4267

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

Upvotes: 1

Related Questions