Theme Service

Tackling theming can at first seem like a daunting, complex task. In this short example we’ll use a service to communicate between components to affect our global class to

a year ago

Latest Post kubectl: most useful commands (a growing list) by Matthew Davis

Tackling theming can at first seem like a daunting, complex task. In this short example we’ll use a service to communicate between components to affect our global class to enable/disable our dark theme.

The Service

First, let’s create a service which will allow us to share our dark mode boolean between components:

/src/app/theme.service.ts

import { Injectable } from '@angular/core';

@Injectable({
    providedIn: 'root'
})
export class ThemeService {

    /**
     * Variable to hold our setting.
     */
    public darkMode: boolean;

    /**
     * Enable/disable "dark mode" by flipping the bit.
     */
    public toggle(): void {

        this.darkMode = !this.darkMode;

    }

}
theme.services

The Components

Second, let’s inject our service into our components so that we can call toggle():

/src/app/app.component.ts

import { Component }    from '@angular/core';
import { ThemeService } from './theme.service';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: [ './app.component.scss' ]
})
export class AppComponent {

    /**
     * Inject the theme service which will be called by our button (click).
     *
     * @param {ThemeService} themeService instance.
     */
    public constructor(public themeService: ThemeService) {

    }

}
components

/src/app/child/child.component.ts

import { Component }    from '@angular/core';
import { ThemeService } from '../theme.service';

@Component({
    selector: 'app-child',
    templateUrl: './child.component.html',
    styleUrls: [ './child.component.scss' ]
})
export class ChildComponent {

    /**
     * Inject the theme service which will be called by our button (click).
     *
     * @param {ThemeService} themeService instance.
     */
    public constructor(public themeService: ThemeService) {

    }

}
chid.component

Applying the Theme

Applying our class is as simple as using the attribute binding below:

<div class="wrapper" [class.dark-mode]="themeService.darkMode">

    <div class="text">

        Dark Mode Enabled? {{ themeService.darkMode ? 'YES' : 'NO' }}

    </div>

    <div class="button">

        Parent Component

        <button (click)="themeService.toggle()">Toggle!</button>

    </div>

    <app-child></app-child>

</div>
darkmode

As you can see all that it takes is using dependency injection to share our toggle method and state. between components.

Source Code

This brief tutorial is accompanied by the project https://github.com/mateothegreat/ng-byexamples-theme-service.

Matthew Davis

Published a year ago

Comments?

Leave us your opinion.