Is there a more efficient method for updating icon paths when switching themes in ThemeService?

I have developed a theme change service for switching icons. Within my theme service, I use BehaviorSubject to manage the path of icons - light theme icons are stored in "assets/light-icons" and dark theme icons are stored in "assets/dark-icons." I inject my service into every component's constructor, passing the folder name as a string based on the selected theme.

Here is an example TypeScript class:

constructor(public themeService: ThemeService) {}

And here is an example HTML class:

<img [src]="'assets/'+themeService.functionWhichReturnsSubjectValueAsString+'/target_icon.svg'">

While this solution works well, I am curious if there is a more efficient approach. Currently, I need to inject my service in each component that contains icons or images. Is it possible to manage this at the parent level?

Answer №1

You can also utilize css variables without specifying a value for [src] or [attr.src]. For more information, refer to this thread on Stack Overflow

Additionally, you need to pass it as SecurityTrustUrl. Consider a styles.css like this:

body {
  --background-color: #fff;
  --text-color: #212a2e;
  --link-color: #543fd7;
  --url-path:'https://picsum.photos/'
}

body.dark {
  --background-color: #212a2e;
  --text-color: #F7F8F8;
  --link-color: rgb(130, 255, 161);
  --url-path:'https://dummyimage.com/'
}
body{
  color:var(--text-color);
  background-color:var(--background-color);
}
a{
  color:var(--link-color);
}

A sample component could look like this:

customProps = window.getComputedStyle(document.body);
constructor(public satinizer:DomSanitizer){}
toogle()
{
document.body.classList.toggle('dark');
}
getImg(value:String)
{
return this.satinizer.bypassSecurityTrustUrl(
this.customProps.getPropertyValue('--url-path').replace("'","").replace("'","")
+value);
}

Then use it like:

<img [attr.src]="getImg('200')">

Check out the example on StackBlitz

Update Actually, SecurityTrustUrl is not necessary

Try something like this instead:

 <img [attr.src]="'http://' + customProps.getPropertyValue('--url-path') + '200'">

where the properties are defined as:

--url-path:picsum.photos/;

//or 

--url-path:dummyimage.com/;

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

What is the best way to clear data in a block after it has been clicked

Whenever the user clicks the "Load new data" button, it displays the data in the template. How can we ensure that old data is cleared after each click until new data is loaded? Additionally, the "Open card" button disappears after being clicked. I attempt ...

Does Highchart offer support for drilling down into sub-categories?

I want to implement a sub-sub drill down feature in my Chart using the following code snippet. // Create the chart Highcharts.chart('container', { chart: { type: 'column' }, title: { text: 'Highcharts m ...

Exploring the functionality of this TypeScript code: What's the distinction between { [key: string]: string }[] and { prop1: string, prop2: string }[]

Below is the code I am currently working with: get tags(): { [key: string]: string }[] { let tags: { [key: string]: string }[] = []; if(this.tags) { Object.keys(this.tags).forEach(x => { tags.push({ prop1: this.tags[x], prop2: g ...

Struggling to enter the command `zip` and accurately anticipating when inference fails in overloaded functions involving generics

There are times when I encounter this issue without understanding why the inference fails. Specifically, zip behaves correctly when directly used, but not when used within pipe, leaving me puzzled. declare const zip: { <A, B>(input: readonly [re ...

Upgrade from RxJS 4 to RxJS 6

How can I convert this Rxjs 4 code snippet to Rxjs 6? const click$ = Rx.Observable.fromEvent($('.btn'), 'click').share(); click$ .scan((a, b) => a + 1, 0) .bufferTime(4000, null, 3) .filter(buffer => buffer.length > 0) ...

Tips for embedding Apache Superset visualizations into an Angular 7 app: Overcoming hurdles with authentication and headers

I am currently working with Apache Superset to create charts. I am looking to embed these charts in my Angular 7 application using an iframe. One major problem I encountered is an authentication failure with the following error message: Refused to display ...

Utilizing Angular's asynchronous validators to handle incoming response data

Struggling with async validators in Angular and trying to implement Container/Presentational Components architecture. Created an async validator to check for the existence of an article number, with the service returning detailed information about the arti ...

Navigating a page without embedding the URL in react-router-dom

In my application, I am utilizing react-router-dom v5 for routing purposes. Occasionally, I come across routes similar to the following: checkup/step-1/:id checkup/step-2/:id checkup/step-3/:id For instance, when I find myself at checkup/step-1/:id, I int ...

How to style the initial selection in a p-dropdown from PrimeNG using CSS

Struggling with customizing a single option in the p-dropdown element of my primeng app. Not sure how to achieve this, can anyone help? <p-dropdown id="dropdown" [options]="options" optionLabel="name" optionValue="name ...

The error message stating that 'children' property is missing in the 'IntrinsicAttributes' type is displayed

I'm attempting to convert my code from pure JavaScript to TypeScript. export const Container = ({ as: Element = 'div', children, className, ...rest }) => { return ( <Element {...rest} classNa ...

Uncertainty arises when trying to understand the callback function supplied to the `addEventListener` method in JavaScript

Question: I was recently exploring JavaScript's native addEventListener function. Typically, we use it like this: js selectElement.addEventListener('change', (event) => { const value = event.target.value }); However, when studying the ty ...

Installing a 3rd party plugin in Angular using the Angular-cli tool

When attempting to install angular2-grid on my Angular-cli with version 2.0.0-rc.1, I followed the tutorial exactly as described but encountered an error. zone.js:101 GET http://localhost:4200/node_modules/angular2-grid/dist/NgGrid 404 (Not Found)sche ...

Encountering the error message "No 'Access-Control-Allow-Origin' header is found on the requested resource."

While working with Angular on the frontend and Java Spring on the backend, I encountered an error message stating: 'No 'Access-Control-Allow-Origin' header is present on the requested resource.'. Even though CORS is enabled in my config ...

Ways to troubleshoot this issue: encountering error in Angular v11 - The Schematic workflow has encountered a failure

I keep encountering an error whenever I try to generate a new project Command I used: ng new dron (to create the project) Error message: npm ERR! Found: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1767786463746464572f39253 ...

Error: The service object is unable to bind to ngModel in Angular 5 due to a TypeError, as it cannot read the property 'state' of undefined within Object.eval

Within my service, I have an object declared: public caseDetails = { partyId: '', address: { state: '', city: '', zip: '', street: '' } } I am trying to bind these objects to i ...

Add 'http://' to hrefs that do not have a protocol specified in Angular

I've been trying to come up with a solution to automatically add "http://" to any href links that don't already have it before the link. Here is what I currently have: static correctUrls(input: string): string { // extract all hrefs from the ...

Make sure to clear the browser cache after you have successfully deployed your Angular 7 application on I

@Component({ selector: 'some-component', templateUrl: `./app/component/stuff/component.html?v=${new Date().getTime()}`, styleUrls: [`./app/component/stuff/component.css?v=${new Date().getTime()}`] }) Is it possible to implement this in an ...

How to handle a Node.js promise that times out if execution is not finished within a specified timeframe

return await new Promise(function (resolve, reject) { //some work goes here resolve(true) }); Using Delayed Timeout return await new Promise(function (resolve, reject) { //some work goes here setTimeout(function() { resolve(true); }, 5000); } ...

Angular2 - Retrieve data in XLS format from RestService并下载

I am looking to create a web service using Apache POI to generate an Excel file (xls, xlsx). Below is the snippet of code I have put together: @RequestMapping(value = "/export", method = RequestMethod.GET) public void exportXlsx(HttpServletResponse respon ...

Ionic 3 Storage Timing Explained

I have a scenario where I am trying to load JSON data from storage and display it on the HTML template of my page. However, when I try to do this, I encounter errors suggesting that the information is not yet available upon entering the page. I'm sta ...