简体   繁体   English

在 Angular 输入装饰器中使用装饰器

[英]Using a decorator inside an Angular input decorator

How do I use an Angular Input property as a parameter for a custom decorator?如何使用 Angular Input 属性作为自定义装饰器的参数?

some-component.html一些组件.html

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

some.component.ts 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 :例如,如果您想要所有输入设置log decoratorlog decorator ,您可以使用以下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 :如果您使用@Input() foo@Input() bar ,装饰器将发出以下日志:

decorator: "value"装饰者:“价值”

Running stackblitz运行堆栈闪电战

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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