简体   繁体   English

Angular:如何从自定义装饰器获取ElementRef

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

I'm implementing decorator for Host CSS Variable Binding in Angular5. 我正在Angular5中实现Host CSS变量绑定的装饰器。 However, I can't implement it well as following code. 但是,我不能很好地实现以下代码。 Can I define ElementRef from decorator? 我可以从装饰器定义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) { }
}

thanks. 谢谢。

我认为没有办法将组件的ElementRef注入到您的自定义装饰器中,因为您的装饰器是属性装饰器,而不是类装饰器。

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

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