簡體   English   中英

Angular:如何從自定義裝飾器獲取ElementRef

[英]Angular: How to get ElementRef From Custom Decorator

我正在Angular5中實現Host CSS變量綁定的裝飾器。 但是,我不能很好地實現以下代碼。 我可以從裝飾器定義ElementRef嗎?

export function HostCssVariable(cssVariableName?: string): any {
  return (target, propertyKey: string, descriptor: PropertyDescriptor) => {
    let _value: any;
    return {
      set: function(value) {
        // this.el is defined by TestComponent's constructor
        // Can I define ElementRef in decorator?
        this.el.nativeElement.style.setProperty(`--${cssVariableName}`, value);
        _value = value;
      },

      get: function() {
        return this.el.nativeElement.style.getProperty ?
          this.el.nativeElement.style.getProperty(`--${cssVariableName}`): _value
      },

      enumerable: true,
      configurable: true,
    }
  }
}


@Component({
  selector: 'test-component',
  templateUrl: ...,
  styleUrls: [...]
})
export class TestComponent {

  @HostCssVariable('hoge')
  public hoge: number = 2;

  constructor(private el: ElementRef) { }
}

謝謝。

我認為沒有辦法將組件的ElementRef注入到您的自定義裝飾器中,因為您的裝飾器是屬性裝飾器,而不是類裝飾器。

暫無
暫無

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

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