首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Angular输入装饰器中使用装饰器

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

Stack Overflow用户
提问于 2020-08-25 17:45:31
回答 1查看 186关注 0票数 1

如何使用角度输入属性作为自定义装饰器的参数?

some-component.html

代码语言:javascript
复制
<some-component [key]="'someString'"></some-component>

some.component.ts

代码语言:javascript
复制
export class SomeComponent {
  @Input()
  set key(value: string) {
    @SomeCustomDecorator(value)
  }
}
EN

回答 1

Stack Overflow用户

发布于 2020-08-25 18:30:51

例如,如果您希望所有输入设置器都有一个log decorator,则可以使用以下decorator/function

代码语言:javascript
复制
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;
      }
    }
  }
}

它可以用作以下用途:

代码语言:javascript
复制
@Input() @Log() foo;
@Input() @Log() set bar(v) {
  console.log('set bar: ', v);
}

如果您使用@Input() foo@Input() bar,装饰器将发出以下日志

值装饰器:“

运行stackblitz

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63576171

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档