To efficiently manage css files in your web application, you can manually load and unload them within a main or root component of a subroot module. Let's take the example of a module called websiteMaster with the following structure:
Routes:
// Grouping routes under a parent component
const routes: Routes = [
{ path: '', component: WebsiteMasterRootComponent, children: [
{ path: 'any-path', component: AnyComponent },
{ path: 'any-other-path', component: AnyOtherComponent },
]
}];
The WebsiteMasterRootComponent is responsible for handling the loading and unloading of css files specific to this module.
export class WebsiteMasterRootComponent implements OnInit, OnDestroy {
// List of css files required for this module
private styles = [
{ id: 'css-file-1', path: 'assets/css/css-file-1.css' },
{ id: 'css-file-2', path: 'assets/css/css-file-2.css' },
{ id: 'css-file-3', path: 'assets/css/css-file-3.css' },
];
constructor() {}
ngOnInit() {
this.styles.forEach(style => this.loadCss(style));
}
ngOnDestroy() {
// Remove css files from the DOM when the component is being destroyed
this.styles.forEach(style => {
let element = document.getElementById(style.id);
element.parentNode.removeChild(element);
});
}
// Append css file dynamically to the DOM when the current module is loaded
private loadCss(style: any) {
let head = document.getElementsByTagName('head')[0];
let link = document.createElement('link');
link.id = style.id;
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = style.path;
head.appendChild(link);
}}