How to add multiple styles to the native element in Angular
Asked Answered
D

2

5

I'm trying to add multiple styles to the native element in angular, currently using the renderer2 API.

I've a requirement in which the styles will change dynamically and it can have many styles. That's why I'm not using the class (addClass/removeClass).

constructor( private elRef: ElementRef, private renderer: Renderer2 )

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

need a way to add the styles dynamically. something like: this.renderer.setStyle(this.elRef.nativeElement, {style1: value1, style2: value2});

Dustin answered 15/1, 2019 at 15:53 Comment(0)
Y
3

You have to call it multiple times for each style or simply use addClass and define styles in class.

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

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

Yeld answered 15/1, 2019 at 16:3 Comment(0)
D
19

try this

 constructor(private element: ElementRef){
    let el = this.element.nativeElement;
    el.setAttribute('style', 'color: white; background: red');
  }
Distaste answered 1/3, 2020 at 12:21 Comment(0)
Y
3

You have to call it multiple times for each style or simply use addClass and define styles in class.

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

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

Yeld answered 15/1, 2019 at 16:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.