【问题标题】:How to add multiple styles to the native element in Angular如何在 Angular 中为原生元素添加多种样式
【发布时间】:2019-06-09 16:08:25
【问题描述】:

我正在尝试向原生元素添加多种样式,目前使用renderer2 API。

我的要求是样式会动态变化,并且可以有多种样式。这就是为什么我不使用类(addClass/removeClass)。

构造函数( 私人 elRef:ElementRef, 私有渲染器:Renderer2 )

this.renderer.setStyle(this.elRef.nativeElement, "text-align", "center"); …… ...

需要一种动态添加样式的方法。就像是: this.renderer.setStyle(this.elRef.nativeElement, {style1: value1, style2: value2});

【问题讨论】:

    标签: javascript angular angular-renderer2


    【解决方案1】:

    您必须为每种样式多次调用它,或者只需使用addClass 并在类中定义样式。

    https://angular.io/api/core/Renderer2#addclass

    https://angular.io/api/core/Renderer2#setStyle

    【讨论】:

      【解决方案2】:

      试试这个

       constructor(private element: ElementRef){
          let el = this.element.nativeElement;
          el.setAttribute('style', 'color: white; background: red');
        }
      

      【讨论】:

        猜你喜欢
        • 2019-03-27
        • 2021-05-27
        • 2018-01-22
        • 1970-01-01
        • 2013-08-21
        • 2018-01-15
        • 2022-01-10
        • 1970-01-01
        • 2014-11-19
        相关资源
        最近更新 更多