Angular Obsidian Theme

Hey there! I've successfully implemented a toggle button that switches my Ionic 3 app to dark mode. However, I'm unsure about where exactly I should define the global class [class.dark-theme]="dark". It's essential for this class to be in the app.component.ts file in order to apply the changes throughout the entire app. Here's what I have done so far:

Here's the code snippet from any-page.html:

<ion-item>
    <ion-label>
      Dark Mode
    </ion-label>
    <ion-toggle [(ngModel)]="dark"></ion-toggle>
  </ion-item>

And here's the content of variable.scss:

.dark-theme {
  ion-label{
    font-size: 33pt;
  }
}

In app.component.ts, I have defined the following:

export class MyApp {
  dark=false;
}

Can you provide guidance on how I can properly define the class for NgModel="dark" as ([class.dark-theme]="dark")? Thanks!

Answer №1

Incorporating a Dark Theme is something I've also accomplished, although using Angular instead of Ionic. The goal is to insert a dark class within the body element. Below, you'll find the code I used:

To begin, create a dark-mode.component component:

import { DOCUMENT } from '@angular/common';

export class DarkModeComponent implements OnInit {

  private class = 'dark';
  private storage = 'darkMode';

  @Input()
  get value(): boolean {
    return this.document.body.classList.contains(this.class);
  }

  set value(isDark: boolean) {
    localStorage.setItem(this.storage, isDark.toString());

    if (isDark) {
      this.document.body.classList.add(this.class);
    } else {
      this.document.body.classList.remove(this.class);
    }
  }

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

  ngOnInit() {
    const value = localStorage.getItem(this.storage);
    if (value) {
      this.value = JSON.parse(value);
    }
  }
}

I'm utilizing local storage to store the user's preference. Here's how the HTML looks:

<span (click)="value = !value">Switch theme</span>

The next step was importing this component into my app.module.ts file:

@NgModule({
  declarations: [
    AppComponent,
    ...
    DarkModeComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    MaterialModule,
    ...
  ],
  providers: [...],
  bootstrap: [AppComponent],
})
export class AppModule { }

Finally, all that's left to do is include your component in an HTML template, as I did in menu.component.html:

<dark-mode></dark-mode>

I trust this information proves helpful.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Typescript to inherit from several classes with constructors

I am trying to have my class extend multiple classes, but I haven't been able to find a clean solution. The examples I came across using TypeScript mixins did not include constructors. Here is what I am looking for: class Realm { private _realms: C ...

Should you approach TypeScript modules or classes with a focus on unit testing?

When it comes to unit testing in TypeScript, which content architecture strategy is more effective: Creating modules or classes? Module Example: moduleX.method1(); // Exported method Class Example: var x = moduleX.method1(); // Public method ...

The Typescript compiler will continue to generate JavaScript code even if there are compilation errors

As a fresh learner of TypeScript, I have been experimenting with some basic concepts. Below is the code from my file app1.ts: class Monster { constructor(name, initialPosition) { this.name = name; this.initialPosition = initialPosition ...

typescript warns that an object may be potentially null

interface IRoleAddProps { roles: Array<IRole> } interface IRoleAddState { current: IRole | null } class RoleAdd extends React.Component<IRoleAddProps, IRoleAddState> { state = { current: null, } renderNoneSelect = () ...

Is there a method to transform the event triggered by a child component via @Output into an observable stream within the parent component?

If we want to trigger a click event from a child component to the parent component, we can use @output in the child component and listen for that event in the parent component using the following syntax: <app-item-output (newItemEvent)="addItem($e ...

Angular Error: Potential security risk detected in resource URL context due to unsafe value being used

Hey there, I'm looking to display a dynamic pdf file. Initially, I encountered a CORS error, but managed to resolve it by using DOM Sanitizer. However, now I'm facing an issue with unsafe URLs. Any assistance would be greatly appreciated. Below ...

The requested resource does not have an 'Access-Control-Allow-Origin' header

- ISSUE: The XMLHttpRequest to 'https://*.execute-api.*.amazonaws.com/api' from 'http://localhost:4200' is blocked by CORS policy. The preflight request doesn't have the necessary 'Access-Control-Allow-Origin' header. ...

Encountering the error message "TypeError: this.http.post(...).map is not a function" after upgrading from Angular 5 to Angular

I encountered some issues with rxjs6 after upgrading from Angular 5 to Angular 6: TypeError: this.http.post(...).map is not a function error TS2339: Property 'map' does not exist on type 'Observable<Object>'. TypeError: rxjs__W ...

The value returned by Cypress.env() is always null

Within my cypress.config.ts file, the configuration looks like this: import { defineConfig } from "cypress"; export default defineConfig({ pageLoadTimeout: 360000, defaultCommandTimeout: 60000, env: { EMAIL: "<a href="/cdn-cgi/ ...

Ensuring the Current Page is Valid Before Progressing to the Next Step in Angular-Archwizard

Currently, I am working with Angular-7 and using angular-archwizard to create a multi-step form. The issue I am facing is that the form allows users to proceed to the next step without filling in all the required fields. My goal is to restrict users from m ...

Ways to initiate a fresh API request while utilizing httpClient and shareReplay

I have implemented a configuration to share the replay of my httpClient request among multiple components. Here is the setup: apicaller.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http& ...

Inserting items into an array entity

I am attempting to insert objects into an existing array only if a certain condition is met. Let me share the code snippet with you: RequestObj = [{ "parent1": { "ob1": value, "ob2": { "key1": value, "key2": va ...

There was a problem encountered while parsing the module due to an unexpected token. It appears that this file type requires a specific loader in order to be properly handled

I am currently experimenting with the Angular map API to track a location in a search box field within Ionic 3. I am encountering an issue that says "Uncaught (in promise): Error: Module parse failed: Unexpected token (91:0). You may need an appropriate l ...

Leveraging ngModel within Form Arrays in Angular 4 with ReactiveFormsModule

While working with simple array forms in Angular 4, I encountered an unusual problem with ngModel ...

Creating interactive buttons in Angular 2

I am currently in the process of coding my own website and I've run into an issue with a button. Here's the code I'm working with: <div *ngFor="let game of games" class=card"> <div class="card-body"> <h5 class="card-t ...

Encountering a 500 error in Angular while utilizing forkJoin for calling API services

In my Angular 7 project, I have implemented a call in the ngOnInit method to two different API routes to fetch some data using forkJoin. Here is how I have set it up: ngOnInit() { debugger this.route.params.pipe( switchMap(params => for ...

Extending Mongoose's capabilities with header files for the "plugin" feature, utilizing the .methods and .statics methods

My task is to develop Typescript header files for a script that enhances my Mongoose model using the .plugin method. The current signature in the Mongoose header files looks like this: export class Schema { // ... plugin(plugin: (schema: Schema, opt ...

React TypeScript - creating a component with a defined interface and extra properties

I'm completely new to Typescript and I am having trouble with rendering a component and passing in an onClick function. How can I properly pass in an onClick function to the CarItem? It seems like it's treating onMenuClick as a property of ICar, ...

Searching for the position of different size values according to their specific value

information = { boxNoTo: 1, boxNoFrom: 1, size: 'M', } items = [{ size: 'M', },{ size: 'M', },{ size: 'S,M,L,XS', boxNoTo: 1, boxNoFrom: 1, country: 'CA', name: 'Josh' }] This is what I have don ...

What is the best method for incorporating Angular 2 files into a Django template?

My application structure is set up like this: ├── project | |── templates │ │ └── index.html │ ├── __init__.py │ ├── models.py │ ├── urls.py │ ├── serializers.py │ ├── views.py ...