📜  renderer.setElementStyle - Javascript (1)

📅  最后修改于: 2023-12-03 15:04:53.193000             🧑  作者: Mango

renderer.setElementStyle - JavaScript

The renderer.setElementStyle method in JavaScript is used to update and apply the specified CSS styles to an HTML element that is selected using a renderer.

Syntax
renderer.setElementStyle(element: any, styleName: string, styleValue: any): void
Parameters
  • element: The HTML element to which the CSS styles will be applied.
  • styleName: The name of the CSS style to be updated and applied to the specified HTML element.
  • styleValue: The updated value of the specified CSS style.
Example
import { Component, Renderer2, ElementRef } from '@angular/core';
 
@Component({
  selector: 'example-selector',
  templateUrl: './example.component.html'
})
export class ExampleComponent {
  constructor(private renderer: Renderer2, private elRef: ElementRef) {}
 
  changeBackgroundColor() {
    const element = this.elRef.nativeElement.querySelector('.example-class');
    this.renderer.setStyle(element, 'background-color', '#444');
  }
}

In the above example, we first get the reference to the HTML element using the elRef variable, and then select the class name using the querySelector method. Next, we use renderer.setStyle to update and apply the new CSS style to the selected HTML element.

Conclusion

The renderer.setElementStyle method is a powerful tool for updating and applying CSS styles to selected HTML elements in JavaScript. It is commonly used in Angular applications for applying dynamic styles based on user interaction or other event triggers.