How to apply styles to elements by selecting using class names in angular?

Viewed 875

This is about an angular css styling app. So as soon as the user applies css styles it gets applied to each element using the renderer2.

Following is a sample key value pair of a style.

const style = {key: 'background-color', value: 'blue'}

The style and element will be passed by the template (i.e. the above method is called inside the template)

<button (click)="setStyle(style, element)">
</button>

But I want to query select each element by it's class names then I want to apply the styles as follows:

constructor(private renderer: Renderer2) {

}

setStyle(style, element) {
this.renderer.setStyle(document.getElementsByClassName(element.className)[0], style.key, style.value
}

But it seems like the above approach is not working.

Is there a way to style an element first by selecting it by class name then styling it? (or may be adding a class dynamically with the new styles - but remember this class is not already defined in the css rules/ definitions; instead created as we go)

NOTE The main idea is to locate an element by class name and then style it.

1 Answers

This would not be the correct approach yet there's a solution. My suggestion would be to select elements by id and not by class. By using ID, only a single element would be returned, but by using class, a list of elements would be returned.

Note: You can add an if condition to check for the particular element that you want and then add class to it.

component.ts file

import { Component, , ElementRef, AfterViewInit } from '@angular/core';
.
.
constructor(private elementRef: ElementRef){};

 ngAfterViewInit(){
    const dom: HTMLElement = this.elementRef.nativeElement;
    const elements = dom.querySelectorAll('.class-to-select')
    elements.forEach((domElement)=>{
      domElement.classList.add('myNewClassToAdd');
    })
  }

component.css file

.myNewClassToAdd{
   font-family: monospace;
   color: tomato;
}

Hope it helps!!.. Happy Coding!!

Related