【问题标题】:Angular - Can you use a click function to change the style of an element in another component?Angular - 你可以使用点击功能来改变另一个组件中元素的样式吗?
【发布时间】:2022-12-14 18:09:50
【问题描述】:

我在一个组件中有这个按钮,当有人点击它时,它会改变我应用程序中许多元素的样式。我面临的问题是我的函数只适用于点击函数所在组件内的 css 类。这是我的函数的工作原理:

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';
    }
  }

我可以使用相同的功能来更改应用程序中另一个组件内元素的样式吗?如果没有,创建一个按钮的最佳方法是什么,单击该按钮会更改我应用程序内不同组件中的许多样式?

【问题讨论】:

    标签: javascript html css angular typescript


    【解决方案1】:

    如果您正在尝试实现“切换暗/亮模式”按钮,那么我建议您看看如何使用 css 实现主题。

    如果不是,那么因为您正在尝试更改应用程序内任意组件的类,所以我建议:

    • 使用像 redux 这样的状态管理库,将 classes 放在 states 到你的 store
    • 实施跟踪所有这些类的服务:
    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>
    

    【讨论】:

    • “类 StylingService”应该在 service.ts 文件中? “class SomeComponent”应该放在哪里?
    • 这是您要更改样式的“许多元素”之一
    【解决方案2】:

    角度方式: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);
        }
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-01
      • 2011-12-14
      • 1970-01-01
      • 2020-03-17
      • 2011-08-31
      • 2023-04-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多