簡體   English   中英

在 Angular 輸入裝飾器中使用裝飾器

[英]Using a decorator inside an Angular input decorator

如何使用 Angular Input 屬性作為自定義裝飾器的參數?

一些組件.html

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

some.component.ts

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

例如,如果您想要所有輸入設置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;
      }
    }
  }
}

它可以用作以下內容:

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

如果您使用@Input() foo@Input() bar ,裝飾器將發出以下日志:

裝飾者:“價值”

運行堆棧閃電戰

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM