While translating in Angular's dark mode, I noticed that the background property disappears from the card-content

`I implemented a toggle-switch in my Angular project using <mat-slide-toggle></mat-slide-toggle> to switch between dark mode and light mode. However, when I switch to dark mode and translate my application, the background property of the card-contents disappears. You can see the issue in this GIF: (https://i.sstatic.net/fXN99.gif)

I attempted to add the dark-theme mode through functions in my application. However, the background object still disappears in the card-content when I translate in dark mode.

This is the section in my home-component.html where the issue occurs:

<section>
<div class="container">
    <h1 class="products-title">New Arrivals</h1>
    <div class="products-list">
      <div *ngFor="let product of products" class="card">
        <div class="card-content" [ngStyle]="{'background-color': isDarkTheme ? '#5eda5e' : '#3b5b2d'}">
          <img class="product-image" [src]="product.imgSrc" [alt]="">
          <h2 class="product-title">{{ product.name | translate}}</h2>
          <p class="product-description">{{ product.description | translate}}</p>
          <p class="product-price">{{ product.price | currency:'USD':'symbol':'1.2-2' }}</p>
        </div>    
      </div>
    </div>
  </div>
</section>

And here is my home-component.ts:

import { AfterViewInit, Component, OnInit } from '@angular/core';
import { ProductService } from '../product.service';
import { Product } from '../product.model';
import { TranslateService } from '@ngx-translate/core';
import { Subscription } from 'rxjs';

@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: \['./home.component.css'\]
})
export class HomeComponent implements OnInit, AfterViewInit {
products: Product\[\] = \[\];
isDarkTheme: boolean = false;
langChangeSubscription: Subscription;

constructor(private productService: ProductService, public translate: TranslateService) {
this.translate.setDefaultLang('en');
this.translate.use('en');
translate.addLangs(\['en', 'tr'\]);

    this.langChangeSubscription = this.translate.onLangChange.subscribe(() => {
      this.updateProducts();
    });

}

// Afer View Init method here

// On Init method here

// On Destroy method here

switchLanguage(lang: string) {
this.translate.use(lang);
}

ChangeLang event here

private updateProducts() {
this.products = this.productService.getProducts();
}
}

This is my header-component.html:

<nav class="navigation">
    <ul class="nav-bar" [ngClass]="{'dark-theme-mode':isDarkTheme}">
       <!-- Navigation links here -->
    </ul>
</nav>

This is my header-component.ts:

import { Component, Renderer2 } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';

@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrl: './header.component.css'
})
export class HeaderComponent {
// Header component logic here
}

I am using ngx app for translation. Please excuse any formatting issues as this is my first question.`

Answer №1

If you are looking for a simple solution, then here is the answer:

https://i.sstatic.net/m08up.png

When we modify its value in the code, let's see what happens:

https://i.sstatic.net/nXvd1.png

I have noticed that you can also access the DOM of those cards through the renderer API and update their styles within header.component.ts. However, it is important to note that when you invoke updateProducts in home.component.ts, it will delete all the items and recreate them in the DOM. This is why altering the style in header.component.ts will not have any effect in that scenario. They will be destroyed and remade. Upon recreation, the value of isDarkTheme inside home.component.ts will remain unchanged. Therefore, the solution lies in adding this single line of code:

this.langChangeSubscription = this.translate.onLangChange.subscribe(() => {
      // Update the isDarkTheme value here!
      this.isDarkTheme = localStorage.getItem('theme') === "Dark";
      this.updateProducts();
});

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

The 'src' properties in nextjs/image are of different types and therefore cannot be used interchangeably

I'm currently using React Dropzone to upload multiple images in my basic application. To display the types of images that are being dropped, I created a separate component with TypeScript. However, Next.js is throwing an error when it comes to the ima ...

Omit assets in final version

During development (ng serve), I have specific assets like images and styles that I use. These assets are not needed in the production build as they are provided by a CDN. My requirements are: When using ng serve, I want to serve files from the folder . ...

What are the steps to executing a function that instantiates an object?

Here is an object with filter values: const filters = ref<filterType>({ date: { value: '', }, user: { value: '', }, userId: { value: '', }, ... There is a data sending function that takes an obje ...

From a series of arrays filled with objects, transform into a single array of objects

Upon using my zip operator, I am receiving the following output: [ [Obj1, Obj2, ...], [Obj1, Obj2, ...] ]. To achieve my desired result, I am currently utilizing the code snippet below: map(x => [...x[0], ...x[1]]) I am curious to know if there exists ...

Effortlessly transfer model data to a different component in Angular upon clicking a button

Component A displays a list of Products, each with an option to view the details. When this option is clicked, I want Component B to show a list of items associated with that specific Product. I am having trouble passing the selected Product from Componen ...

Can someone guide me on integrating a React Material-UI Component into an Angular2 application?

I've been searching for documentation on integrating ng2 and React, but it's been hard to find any solid information. It's making me question whether or not these two can actually work together. Since I'm not an expert, I could really u ...

List the attributes that have different values

One of the functions I currently have incorporates lodash to compare two objects and determine if they are identical. private checkForChanges(): boolean { if (_.isEqual(this.definitionDetails, this.originalDetails) === true) { return false; ...

Checkbox selection limitation feature not functioning correctly

Having trouble with my checkbox question function - I want to limit the number of checkboxes that can be checked to 3, but it's still allowing more than that. I suspect the issue lies with latestcheck.checked = false; This is my typescript function: ...

Requirements for Method Decorators - The complete path of the class module using the decorator must be provided

Upon running the decorator (method decorators) function, we are provided with access to target, methodName, and descriptor. I am seeking the module path for target in this specific scenario. Essentially, I want the file path that points to the module that ...

Launch the Image-Infused Modal

I am completely new to the world of Ionic development. Currently, I am working on a simple Ionic application that comprises a list of users with their respective usernames and images stored in an array. Typescript: users = [ { "name": "First ...

Implementing TypeScript type declarations for merging core types

Is there a way to perform type declaration merging in TypeScript for built-in types when using imports? I am currently attempting to merge interfaces as per the guidelines outlined in this documentation: https://www.typescriptlang.org/docs/handbook/declar ...

To trigger a Bootstrap 5 modal in a child component from a button click in the parent component in Angular without the need to install ng-bootstrap is possible with the following approach

To achieve the functionality of opening a modal in a child component upon clicking a button in the parent component without using ngx-bootstrap due to restrictions, one approach is to add data-bs-target and data-bs-toggle attributes to the button. Addition ...

Guide to dynamically updating image URLs based on color selection in Angular when handling ngFor loop

component.ts // necessary imports have been included ngOnInit() { this.list = { 'eatList': [{ 'class': 'Fruits', 'color': ['Red', 'White', 'Black& ...

The variable <variable> is not meeting the 'never' constraint. Error code: ts(2344)

Currently, I am attempting to utilize Supabase alongside TypeScript. However, I encounter an error when trying to use functions like insert(), update(), upsert(), etc. Specifically, the issue arises when declaring the object I want to declare: "Type & ...

Ways to update the component's state externally

I'm new to Next.js (and React) and I'm attempting to update the state of a component from outside the component. Essentially, I am conditionally rendering HTML in the component and have a button inside the component that triggers a function to se ...

What strategies can be used to prevent circular dependencies within components?

In my application, the root component is named app-document-form and it iterates through the children elements of an object called documentBlock: <ng-container *ngFor="let element of documentBlock?.children"> <!-- This part is crucial -- ...

I am experiencing an issue where the Javascript keydown event does not recognize the character "@" in the EDGE browser

Currently, I am developing a mentioning directive that displays a list of users when the user types in an input field (a div with contentEditable=true). The user can then insert the name of the desired user in a specific format. The list is supposed to be ...

The data in ag Grid does not display until all grid events have been completed

After setting the rowData in the onGridReady function, I noticed that the data does not display until all events are completed. I also attempted using the firstCellrendered event, but unfortunately, it did not resolve the issue. OnGridReady(){ this.r ...

Using ngrx to automatically update data upon subscription

Background The technology stack I am using for my application includes Angular 4.x, ngrx 4.x, and rxjs 5.4.x. Data is retrieved from a websocket as well as a RESTful API in order to share it between multiple components through ngrx. Currently, data is ref ...

Testing Angular Components with Jasmine and Karma: When handling the 'onChange' event, the changeEvent parameter of type MatRadioChange should not be void and must be assigned to a parameter of type

Hey there, I was working on a test for a call where I am using to emit the event: onChange(eventName: MatRadioChange): void { this.eventName.emit(eventName.value); } Here is the test I have written for it: describe('onChange', (eventName: ...