简体   繁体   中英

Angular: How to get ElementRef From Custom Decorator

I'm implementing decorator for Host CSS Variable Binding in Angular5. However, I can't implement it well as following code. Can I define ElementRef from decorator?

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注入到您的自定义装饰器中,因为您的装饰器是属性装饰器,而不是类装饰器。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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