简体   繁体   中英

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.

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.

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

eg

//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, eg

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM