首页 > 解决方案 > 在 Angular 8 中根据所选主题(在 ui 中选择)更改 css 类的属性

问题描述

我有一个 Angular 8 应用程序,而用户可以在 ui 中的两个不同主题之间切换。我在 div 上有一个类,我希望每个主题的背景颜色都不同。但我无法做到这一点。

也许这里有人以前做过类似的事情?

Myapp.component.html

<div class="ui-layout">
    <div class="card">
        <div class="wrapper">


        </div>
    </div>
</div>

Myapp.component.scss

.card {
  background-color: #ffffff;
}

.black-blue-theme {
    .card { 
    background-color: #424242 !important;
    }
}

app.component.ts

  ngOnInit() {
        this.componentCssClass = 'light-indigo-theme';
        themes.current('generic.light');
        this.setupOverlayContainer();
        this.subscribeToObservableFooter();

    }

    setupOverlayContainer() {
        const containerElement = this.overlayContainer.getContainerElement();
        if (containerElement) {
            const classList = this.overlayContainer.getContainerElement().classList;
            const toRemove = Array.from(classList).filter((item: string) =>
                item.includes('-theme'),
            );
            classList.remove(...toRemove);
            classList.add(this.componentCssClass);
        }
    }

    changeTheme(type: string) {
        this.componentCssClass = type;
        if (type === 'black-blue-theme') {
            themes.current('generic.dark');
        } else {
            themes.current('generic.light');
        }
        this.setupOverlayContainer();
    }

标签: cssangularsassangular8theming

解决方案


您有两个主题,默认情况下应使用其中一个。好的,让我们做这样的事情。

app.component.ts

currentTheme: string = 'generic.dark';

changeTheme(type: string) {
    this.currentTheme = type;
}

app.component.html

<div class="ui-layout" [ngClass]="currentTheme">
    <div class="card">
        <div class="wrapper">


        </div>
    </div>
</div>

推荐阅读