Angular 如何给原生元素添加多种样式

How to add multiple styles to the native element in Angular

我正在尝试向 angular 中的原生元素添加多种样式,目前使用的是 renderer2 API.

我有一个需求,其中的样式会动态变化,并且可以有多种样式。这就是为什么我不使用 class (addClass/removeClass).

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

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

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

您必须为每个样式多次调用它或简单地使用 addClass 并在 class 中定义样式。

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

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

试试这个

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