Style Modes
Style modes give one component several stylesheets, and pick one for each instance at runtime. Ionic uses them to render the same components with iOS or Material Design styling.
Give styleUrls an object, with a stylesheet for each mode. The mode names are up to you:
@Component({
tag: 'simple-button',
styleUrls: {
md: './simple-button.md.css',
ios: './simple-button.ios.css',
},
})
export class SimpleButton {
// ...
}
Choosing a Mode
Call setMode() with a function that returns the mode for an element. Stencil calls it once for each component instance, before its first render. This example reads the element's mode attribute and falls back to md:
import { setMode } from '@stencil/core';
export default () => {
setMode((el) => el.getAttribute('mode') || 'md');
};
<simple-button mode="ios"></simple-button>
setMode() has to run before any component renders, so call it from your global script. Stencil uses src/global.ts as the global script automatically.
A component with style modes gets no styles at all if no mode is set, or if the mode it's given has no stylesheet. A component's mode is fixed once it has loaded; to change it, render a new element.
In this playground, change a mode attribute in index.html to web, which has no stylesheet, and that button loses its styles:
<script type="module" src="./simple-button.js"></script>
<simple-button mode="ios">iOS</simple-button>
<simple-button>Material (the default)</simple-button>
import { Component } from '@stencil/core';
@Component({
tag: 'simple-button',
styleUrls: {
md: './simple-button.md.css',
ios: './simple-button.ios.css',
},
encapsulation: { type: 'shadow' },
})
export class SimpleButton {
render() {
return (
<button>
<slot />
</button>
);
}
}
button {
padding: 8px 16px;
border: 0;
border-radius: 4px;
background: #6200ee;
color: white;
text-transform: uppercase;
}
button {
padding: 8px 16px;
border: 1px solid #007aff;
border-radius: 10px;
background: white;
color: #007aff;
}
Reading the Mode
getMode() returns the mode a component was given:
import { getMode } from '@stencil/core';
const button = document.querySelector('simple-button');
console.log(getMode(button)); // 'ios'