Search code examples
cssangulartypescriptstyleshtmlelements

Angular, apply a style on a HTMLElement


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.


Solution

  • 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.