简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM