What is the best way to retrieve the current theme's palette colors in Angular Material using JavaScript?

In angular-material, color palettes can be defined in an angular config block like this:

angular.module('myApp', ['ngMaterial'])
.config(function($mdThemingProvider) {
  $mdThemingProvider.theme('default')
    .primaryPalette('pink')
    .accentPalette('orange');
});

It's quite impressive...

However,

The issue arises when trying to use the current color value of a specific palette on custom elements that are not natively supported. The list of natively supported elements includes:

  • md-button
  • md-checkbox
  • md-progress-circular
  • md-progress-linear
  • md-radio-button
  • md-slider
  • md-switch
  • md-tabs
  • md-text-float
  • md-toolbar

For more information, visit: https://material.angularjs.org/latest/Theming/02_declarative_syntax

Unfortunately, custom elements are not supported.

So how can we apply the current value of a specific palette within a theme to custom DOM elements or nested elements?

I have searched through the API and couldn't find any solution.

An ideal scenario would be to have a service that exposes methods for accessing theme palettes, such as:

$mdTheme.getTheme('default');

This method should return an object containing all the palettes defined in the theme.

EDIT : Here is an example of how it could be used

This may not be the most elegant code design, but it gets the job done

Once we have access to the theme palettes, we can use them in custom or native directives:

// controller:
angular.module('myApp').controller('myCtrl',function($scope,$mdTheme){

  var primary500 = $mdTheme.getTheme('default').getPalette('primary').getHue('500');

  $scope.customStyleBorderPrimary = {
    'border-bottom': 'solid 2px ' + primary500
  };

}

And then

<!-- in view -->
<h4 ng-style="customStyleBorderPrimary" ng-controller="myCtrl">
  My h4 title with primary border-bottom
</h4>

Answer №1

I recently developed a set of practical directives within an angularjs module called swapMdPaint, which is available in a bower package named swap-md-paint.

Explore, documentation, and downloads

https://github.com/rbecheras/swap-md-paint

Installation process

To install this module, follow these steps:

bower install swap-md-paint --save

Alternatively, you can search for it manually at:

or perform the installation via git clone:

git clone https://github.com/sirap-group/swap-md-paint.git public/lib/swap-md-paint
cd public/lib/swap-md-paint
git checkout v0.4.0

Integration

Incorporate this module into your application by:

First, include

public/lib/swap-md-paint/swap-md-paint.min.js
in the body tag of your index.html

Then, add swapMdPaint as a dependency to your application.

Usage guide

Here's how you can utilize this module:

Select the default theme's accent color

<div swap-md-paint-fg="accent">Default Themes Accent Color</div>

Or opt for the default themes primary palette with hue-1 and more:

<div swap-md-paint-fg="hue-1">Default Themes Primary Palette Hue-1</div>

You have the option to specify the intent palette (

[primary], accent, warn, background
) and hue using theme([default])

[ ] => defaults if no input is provided.

  • swap-md-paint-fg adjusts the css color of the element
  • swap-md-paint-bg alters the css background-color of the element
  • swap-md-paint-bg modifies the css fill of the element

If utilizing the -svg directive, ensure to include

md-icon {
  fill:inherit;
}

( Or a more specific selector ) to apply colors to svg-based icon buttons

 Connect on github !

Feel free to connect with me on Github: https://github.com/rbecheras/swap-md-paint

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

Tips for adjusting page content responsively when toggling the sidebar

I am in the process of designing a website that includes a left sidebar and Bootstrap 4 fixed size cards in the main content area. However, when the viewport size is toggled from >768px to smaller sizes, the page content does not respond as expected, r ...

Tips for aligning carousel indicators vertically in Bootstrap 5

I am struggling to vertically align the carousel indicators in Bootstrap 5. The solutions I have found so far are for Bootstrap 4, but they do not seem to work for me. Here is the markup for my carousel indicators. <div class='carousel-in ...

Struggling to get Canvas2ImagePlugin to function properly within an Ionic app and Angular.js

Recently, I stumbled upon a plugin that allows me to save images in my App, a solution I have been struggling to find. My question is: how do I integrate this into an angular framework? As a newcomer to angular.js, I'm feeling quite lost. The code sni ...

Can dynamic attributes be used with ternary operators in Angular?

I attempted to alter the id of a div using Angular and implemented the following code: <div [id]="'item_' + (itemName !== undefined ? itemName.replace(' ', '-').toLowerCase() : '')"> However, when I run my te ...

Blocking Main Thread Issue with Large Datasets in WebDataRocks Configuration

My Vue 3 project is utilizing WebDataRocks to manage large datasets. While the implementation works well with smaller datasets, it faces performance issues as the data size grows due to the setReport method blocking the main thread. Below is a simplified v ...

The functionality of minified JS code is limited to being copied and pasted directly into the

Trying to explain the issue I'm facing may be a bit tricky, but here it goes: I've been working on an AngularJS app (not live yet) and we felt the need to add tooltips for specific metrics in our tables. After some research, we really liked the ...

Using Angular, the $http.post method is utilized to send data in JSON format

I am working with a JavaScript variable that is an array of objects. To display this variable in the view, I am using the code below: <tr ng-repeat="user in lala.users"> <td>{{ user.firstName }}</td> <td>{{ user ...

Troubleshooting React Native in VS Code using Node shims

I recently started working on a React Native project using the Ignite CLI 2.0.0 default boilerplate, and I find myself in need of some dependencies from node-based packages. To address this, I created files named transformers.js, babel-transform.js, and r ...

Having Trouble Changing CSS with Rails Link_to CSS ID

While following the ruby on rails guide, I came across a specific way to write link_to's with a css id: <%= link_to "About", about_path, id: "third" %> I also attempted: <%= link_to ("About", :id => "third"), about_path %> Although ...

The issue of why iterating over an array of objects does not function properly in React JS

P.S: I have made some modifications to the code below. Extracting the doctor's value from JSON data, updating the state, and then mapping it to print out the values. Initially, there is only one doctor, but in the future, there could be more than one ...

What is the best way to trigger a snackbar notification when two passwords do not match?

I'm currently developing a full stack application and I am facing an issue with displaying a snackbar in my signup component when the user's password and confirm password do not match. I have been advised to pass the setOpenAlert method as props ...

Error in Next.js: react-dom.development.js?ac89:14906 - Hook call is invalid. Hooks should only be used within a function component's body

Here is the code snippet I am working with: <div onClick={(e) => handleClick()}>Join Us</div> This is the handleClick function in my code: const handleClick = () => { console.log(Lang.getLocale()) }; And this is the Lang class metho ...

Rails - Issue with jQuery/AJAX causing partial not to refresh

Currently, I have a timeline view that displays event partials, allowing users to create, read, update, and delete events directly on the timeline. However, I am facing an issue where the delete partial does not refresh after deleting an event, requiring t ...

What is the solution for handling nested promises in Node.js?

I am currently using the node-fetch module for making API calls. I have a function that handles all the API requests and returns both the status code and the response body. The issue I'm facing is that when returning an object with the response data, ...

Tips for managing modal closure when the InertiaJS form succeeds?

Hello everyone! Currently, I'm involved in a Laravel project where I am using laravel/breeze VueJS with Inertia. The login functionality is implemented using a bootstrap modal component. While validation and authentication are working smoothly, the on ...

Any tips on sending looping values to a Bootstrap modal?

Introduction: Despite researching solutions for passing variables into a Bootstrap modal, none of them seem to solve my particular issue. I am currently iterating over a JSON object that contains image URLs and an array of comments related to each image. ...

Misaligned tabs within Bootstrap Modal

Currently, I am working on creating a Bootstrap Modal that includes tabs for easy navigation within the modal. However, I have encountered an issue where the tabs are not aligned properly as shown in the image linked below: View Image Here This is the co ...

Tips for preventing table cells from vertically overflowing and displaying the table without any issues

I have tried numerous solutions from various sources, but none seem to work for my specific issue. My HTML page consists only of a table that I want to print perfectly on a horizontal A4 sheet. Here is the table without any text (it is a match referee): ...

Excess space creating horizontal and vertical scrolling issues on an HTML webpage

Currently, I am experimenting with CSS effects. In my code, I have included div elements to display balls on the document body, each with random sizes and colors. However, an unexpected issue has arisen - excess scroll space is being generated due to the c ...

Integrate CSS with a dynamic PHP variable

<?php if ($username) echo $username else echo '<form class="navbar-form navbar-right" action="login.php"> <button class="btn btn-custom">Log ind</button> </form>'; ...