Angular, apply a style on a HTMLElement

1.7k Views Asked by At

I have an issue with Typescript, i'm trying to apply a style on a HTMLElement, here is the code :

 styleChoice(element:HTMLElement){
    console.log(element);
    element.style.background="rgba(228, 48, 48, 0.2)";
    element.style.borderRadius="40px";
  
  }
  test(){
    console.log(document.getElementById('test'));
    this.styleChoice(document.getElementById('test'));
   
  }

I don't understand why is not working.

2

There are 2 best solutions below

0
On BEST ANSWER

You should use the Renderer2 for this to work. It will be a good option. Don't use the document directly in the app, check here for more details.

export class DemoComponent {
  constructor(
    private element: ElementRef,
    private renderer: Renderer2,
  ){

  }

styleChoice(element:HTMLElement){
    console.log(element);
    //element.style.background="rgba(228, 48, 48, 0.2)";
    renderer.setStyle(el, 'background', 'red');
    renderer.setStyle(el, 'borderRadius', '40px');
   // element.style.borderRadius="40px";
  
  }
  test(){
    console.log(document.getElementById('test'));
    this.styleChoice(document.getElementById('test'));
   
  }
}

You can check here for renderer2 documentation.

0
On

This is not an Angular way, an Angular way is to use a variable and [ngStyle]

e.g.

//in .ts
style={
   "background":"rgba(228, 48, 48, 0.2)",
   "borderRadius":"40px"
}
//in .html
<some-element [ngStyle]="style">...</some-element>

//or directly
 <some-element [ngStyle]="{'background':'rgba(228, 48, 48, 0.2)',
                                        'borderRadius':'40px'}">
     ...
 </some-element>

You can change the style according a variable, e.g.

variable=true;
<some-element [ngStyle]="variable?style:null">...</some-element>

If only want to change one property you can use [style.property]

//in .ts
backgroundColor="rgba(228, 48, 48, 0.2)"
//in .html
<some-element [style.background]="backgroundColor">...</some-element>