ossmalpha
ossmalpha

Reputation: 881

Ionic 6 styling of ion-datetime

I have stumbled upon some difficulties styling ion-datetime component using ionic 6, and none of the posts seem to contain a solution for this. I would like to apply some custom styles to picker items that appear in the shadow-root part.

Applying CSS to classes like .picker-item and .picker-item-active doesn't do anything because they are in the shadow-root. And there don't seem to be any styling properties and variables for ion-picker that I could use.

I am using the standard ion-datetime component like this:

<ion-datetime presentation="time"></ion-datetime>

and in the simulator while inspecting the HTML it appears as:

Chrome inspect example

Styling that I would like to change:

Upvotes: 0

Views: 1555

Answers (2)

ossmalpha
ossmalpha

Reputation: 881

After some more playing around, I have been able to find a solution and customize it to my project needs. Thanks to Danny '365CSI' Engelman for inspiration.

The use of ion-datetime and its customization in my project is complex due to using multiple ion-datetime elements appearing and disappearing dynamically. Therefore, applying custom styling of it required some additional logic not posted here. Please reach out if you need some help regarding this.

Here is the base logic that allowed me to apply some styles to ion-datetime:

document.querySelectorAll("ion-datetime").forEach(dt => {
  var el = dt.shadowRoot.querySelector("ion-picker-internal");
  el.shadowRoot.prepend(Object.assign(document.createElement("style"), {
    innerText: `
      .picker-highlight {
        background: red !important;
      }
    `
  }));
  el.querySelectorAll("ion-picker-column-internal").forEach(col => {
    col.shadowRoot.prepend(Object.assign(document.createElement("style"), {
      innerText: `
        .picker-item {
          color: green !important;
        }    
        .picker-item-active {
          color: blue !important;
        }
      `
    }));
  });
});

Upvotes: 0

Since they are all open shadowRoots, you can get in and inject a <style> sheet:

document.querySelector("ion-datetime")
.shadowRoot.querySelector("ion-picker-internal")
.shadowRoot.querySelector("ion-picker-column-internal")
.shadowRoot.prepend( Object.assign( document.createElement("style") , {
  innerText : `
               .picker-item {
                              background:hotpink
                            }
              `
}));

Upvotes: 1

Related Questions