Home > Enterprise >  Angular - Can you use a click function to change the style of an element in another component?
Angular - Can you use a click function to change the style of an element in another component?

Time:07-27

I have this button inside a component and when someone clicks on it it changes the styles of many elements in my app. The problem I'm facing is that my function only works with css classes inside the component where the click function is. Here is how my function works:

HTML

<a role="button" (click)="toggleChange()">button</a>

<div [ngClass]="[divStyle]">test</div>

SCSS

.div-default {
  background-color: #AAA;
}

.div-changed {
  background-color: #BBB;  
}

TS

divStyle = 'div-default';

  toggleChange(): void {

    if (this.divStyle == 'div-changed') {
      this.divStyle = 'div-default';
    } else {
      this.divStyle = 'div-changed';
    }
  }

Can I use this same function to change the style of an element inside another component in my app? If not, what is the best way to create a button that when clicked changes many styles in different components inside my app?

CodePudding user response:

https://angular.io/api/core/Renderer2

  import { Inject, Renderer2 } from '@angular/core';
  import { DOCUMENT } from '@angular/common';

  constructor(
    @Inject(DOCUMENT) private document: Document, 
    private renderer: Renderer2,
  ) {
  }

  toggleChange(): void {
    const element = this.document.body; // for example
    const className = 'example'; // for example
    if (element.classList.contains(className)) {
      this.renderer.removeClass(element, className);
    } else {
      this.renderer.addClass(element, className);
    }
  }

CodePudding user response:

If you're trying to implement a "Toggle Dark/Light Mode" button then I would suggest taking a look at how to implement themes using css.

If not then since you're trying to change classes of arbitrary components inside your app, I would suggest either:

  • Use a state management library like redux and have those classes at states in your store
  • Implement a service which keeps track of all these classes:
class StylingService {
  divStyle = 'div-default';

  toggleChange(): void {
    if (this.divStyle == 'div-changed') {
      this.divStyle = 'div-default';
    } else {
      this.divStyle = 'div-changed';
    }
}
... and then in the component that need to use the class:

class SomeComponent {
  divStyle: string;
  constructor(private stylingService StylingService) {
    this.divStyle = stylingService.divStyle;
  }
}
... the button would look like:
<button (click)="stylingService.toggleChange()">Change class</button>
  • Related