【问题标题】:Angular: How to get ElementRef From Custom DecoratorAngular:如何从自定义装饰器中获取 ElementRef
【发布时间】:2019-03-19 07:06:35
【问题描述】:

我正在 Angular5 中实现宿主 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) { }
}

谢谢。

【问题讨论】:

  • 错误是什么? this.el 未定义?
  • 没有错误。但是这段代码并不聪明。我必须写 constructor(private el: ElementRef) 来使用这个装饰器。
  • @NozomuMiyamoto,开始尝试一个更简单的示例。定义一个应用于属性的装饰器,并在其中将element 属性添加到类并将ViewChild 装饰器应用于它。如果成功,请将逻辑迁移到您的自定义装饰器。

标签: angular typescript decorator


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2013-02-06
    • 2018-07-30
    • 2019-08-04
    • 2020-10-11
    • 1970-01-01
    • 2021-09-26
    • 2018-10-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多