首页 > 解决方案 > 将 ngStyle 绑定到指令的动态 ElementRef

问题描述

我开发了一个指令来动态地将 elementRef 添加到当前元素。是否可以将 ngStyle 指令绑定到动态创建的 elementRef。

  dynamicElementStyle: { [key: string]: string; };

  constructor(private _element: ElementRef, private _renderer: Renderer2) { }

  @HostListener('mouseover') onHover() {
    this.dynamicElementStyle.background-color = "red";
  }

  @HostListener('mouseleave') onHover() {
    this.dynamicElementStyle.background-color = "green";
  }

  public ngOnInit(): void {
    const dynamicElement = this._renderer.createElement('div');
    /* How to bind dynamicElementStyle to this dynamicElement */   
    this._renderer.appendChild(this._element.nativeElement, dynamicElement);
  }

我不会使用 Renderer2.setStyle() 来应用样式,而是使用对象。它可以是 ngStyle 以及 ngClass、ngIf 等......

标签: angulardirective

解决方案


推荐阅读