visit
In certain scenarios, there is a need to fetch styles from the backend. This could be particularly relevant when dealing with private themes or implementing white-label solutions. The backend, in this context, acts as the source of style settings, drawing them either from a database or a YAML file. The specific data source may vary, but the process remains consistent.
Let's assume that the UI is constructed with Angular, although the principles we're about to delve into are versatile and can be applied regardless of the framework you choose, or even if you opt for a framework-less approach.
To start, let's create a service:
@Injectable()
export class StylesService {
defaultStyles: Record<string, string> = {
primary: 'green',
secondary: 'blue',
};
constructor(
private readonly http: HttpClient,
@Inject(DOCUMENT) private readonly document: Document,
) {}
...
}
setStyles(): void {
this.http.get('/styles').subscribe((styles: Record<string, string>) => {
styles = {...this.defaultStyles, ...styles};
localStorage.setItem('currentStyles', JSON.stringify(styles));
this.document.documentElement.style.setProperty('--primary-color', styles.primary || '');
this.document.documentElement.style.setProperty('--secondary-color', styles.secondary || '');
});
}
getStyles(): Record<string, string> {
const styles = localStorage.getItem('currentStyles');
if (styles) {
return JSON.parse(styles) as Record<string, string>;
}
return null;
}
$primary-color: var(--primary-color, orange);
$default-secondary: var(--secondary-color, purple);
a {
color: var(--primary-color, #F69C00);
}
The second parameter of the var()
function comes into play when the variable --primary-color
doesn't exist. It acts as a fallback value, ensuring that your code remains robust even if the primary color variable is not defined.