Theming Angular Libraries (feat. Typescript)

Re-usability is extremely powerful. Make your libraries even more re-usable by allowing them to be themed from apps.

Git repo

Instead of having users sift through lots of documentation to find your css variables and set them themselves, we’re going to use a service.

Step 1:

Get a list over what styles you want your end users to have control over, in our case we want our users to set their own:

  • Background color
  • Text color

Now replace the styling of these properties in your library component with css variables, like’a so:

.custom-box {
background-color: var(--css-component-background-color);
color: var(--css-component-text-color);
}

Step 2:

Now create a component.service.ts file in your library component folder. In this file, first add your theme configuration interface;

export interface CssComponentTheme {
backgroundColor: string;
textColor: string;
}

And here comes the service:

@Injectable({
providedIn: 'root',
})
export class CssComponentService {
setTheme(themeConfig: CssComponentTheme){
document.documentElement.style.setProperty(
'--css-component-background-color',
themeConfig.backgroundColor
);
document.documentElement.style.setProperty(
'--css-component-text-color',
themeConfig.textColor
);
}
removeTheme() {
document.documentElement.style.removeProperty(
'--css-component-background-color'
);
document.documentElement.style.removeProperty(
'--css-component-text-color'
);
}
}

For each extra property you want to make theme-able, add another css variable inside the setTheme function:

document.documentElement.style.setProperty(
'--your-css-variable',
themeConfig.property
);

And add it to the clean-up function as well:

document.documentElement.style.removeProperty(
'--your-css-variable'
);

Step 3:

Export your service and interface from the library public-api.ts:

export * from './lib/css-component/css-component.service';

Service, done.

Now use it in your app:

Import it in a component:

import {
CssComponentService,
CssComponentTheme,
} from 'projects/your-library/src/public-api';
Now you and other beneficiaries of your library get help. No more sweating about remembering propertynames or in which file you can find them.
There, all good

Services go in the constructor:

constructor(private cssService: CssComponentService) {}

Final Touches:

ngOnInit() {
this.cssService.setTheme(this.myTheme);
}
ngOnDestroy() {
this.cssService.removeTheme();
}

Done!

So there you go, type-proof angular library theming using CSS variables.

Go nuts! 😎

Angular developer / Digital marketer