Utilize varied CSS files for distinct sections within two different subdirectories

In my Angular application, I have created two sub-roots under the main app root: websiteMaster and systemMaster. I want the CSS files of the website to be loaded only when a user is logged in, and the CSS files of the systems to be loaded only when a user is logged out. Is there a way in Angular 8 to achieve this, where CSS files are loaded based on the current login status?

Answer №1

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);
}}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for adjusting the width of a div when printing

Imagine I have two container elements named container1 and container2. First, I assign a width of 30% to container1 and 60% to container2. Then add a border between the two containers. However, when I attempt to print, container1 takes up the full 100% o ...

Pass on only the necessary attributes to the component

I have a simple component that I want to include most, if not all, of the default HTML element props. My idea was to possibly extend React.HTMLAttributes<HTMLElement> and then spread them in the component's attributes. However, the props' ...

Unable to assign decimal values to the tooltip value in Angular's Ng bar chart

I'm currently working on my Angular project with ngChartjs, and I've run into a conflict regarding the tooltip values. https://i.sstatic.net/NBKCJ.png For example, if the value is 6131327.319655154, I have tried formatting it to 6131327.31 usin ...

Comparing Angular i18n JSON files automatically for consistency checks

Within my Angular application, I am working with two translation files: en.json and xx.json. While the standard practice is to create translations in both files for a multilanguage application, some developers may only add translations to one file when tes ...

Is it possible to detach keyboard events from mat-chip components?

Is there a way to allow editing of content within a mat-chip component? The process seems simple in HTML: <mat-chip contenteditable="true">Editable content</mat-chip> Check out the StackBlitz demo here While you can edit the content within ...

How can you change the width of <td> and <th> elements?

I am trying to keep a table header fixed at the top of a window, but for some reason, setting the widths of the <td> and <th> elements as shown below is not resulting in them having the same width (the column headers are misaligned with other c ...

Is there a way to make the Sweetalert2 alert appear just one time?

Here's my question - can sweetalert2 be set to only appear once per page? So that it remembers if it has already shown the alert. Swal.fire({ title: 'Do you want to save the changes?', showDenyButton: true, showCancelButton: true, ...

What is the best way to allocate a unique color to every item within an array?

I've been working on some JavaScript code that pulls a random color from a selection: const colors = [blue[800], green[500], orange[500], purple[800], red[800]]; const color = colors[Math.floor(Math.random() * colors.length)]; Within my JSX code, I ...

Is it possible to nest enums within enums in TypeScript programming?

enum TYPES { CODE = 1, TEXT, IMAGE, VIDEO } enum ALL_TYPES { CODE = 1, TEXT, IMAGE, VIDEO, NONE } Is there a way to incorporate the TYPES enum into the ALL_TYPES enum? ...

The issue of multiple routes not functioning properly in a microfrontend application when refreshing the browser is currently being experienced with the single-spa-angular setup. There is code

Looking for some assistance with this issue. Any help would be greatly appreciated. I have a basic angular application with several routes listed below: App1Route1 App1Route2 App1Route3 The main app component utilizes to showcase these routes. https:// ...

Angular 2: Another service is unable to find the custom service

I have a situation where I am using an HttpInterceptor and trying to integrate a NotificationService within it. However, I encountered an issue where the NotificationService appears to be undefined in the httpInterceptor. Is there something that I missed o ...

Unveiling the Quirk of Foundation 5: Grid Encounters a Popping

Recently, I encountered an issue with Foundation 5. Whenever I attempt to apply the "position:fixed" property on a "div" element that is part of the Foundation Grid, it causes the div to break out of the grid and align itself with the left edge of the ro ...

Browser-compatible search bar for numerical values

How can I restrict my search bar to only accept numbers in all browsers? I attempted using type="numbers", but it caused issues with the functionality of my search bar. Suggestions involving JavaScript and JQuery are appreciated. Check out the JSFiddle fo ...

Removing a CSS class using JQuery

Within my website layout, I have a div that is dynamically included using PHP. This div is inserted in two different locations, each inside its own parent div. <div id="parent_div"> <div id="contact_details_div" class="contact_details_div sam ...

Activate the drop-down division when the search box is in focus with xoxco technology

Currently, I am incorporating Xoxco's tag input plugin which can be found at the following link: In my customization, I have implemented JQuery's focus() function <input id="tags_1" class="tag-holder" type="text" class="tags" /></p> ...

What is the best way to invoke a TypeScript function within an HTML document?

Can anyone guide me on how to import a TypeScript function into an HTML file and then call it? I'm a bit confused about the process. Below is my attempt in index.html to call the function getJSON() <!DOCTYPE html> <html lang="en"> < ...

The transition between backgrounds is malfunctioning

I want to create a smooth transition effect for changing the background of an element within a setInterval function. Currently, the background changes immediately, but I would like it to transition over a period of time. var act = true; setInterval(func ...

Guide on creating a Meteor Bootstrap WhatsApp clone

I'm currently going through the step-by-step guide for Whatsapp on the following website: After entering this command: meteor npm install angular@^1.5.8 --save I encountered the following message: no matches found: angular@^1.5.8 Does this mean t ...

Troubleshooting Paths with Angular's NgFor Directive

Within my Angular project, I have implemented a basic ngFor loop to display logo images. Here is a snippet of the code: <div *ngFor="let item of list" class="logo-wrapper"> <div class="customer-logo"> & ...

Using jQuery to organize divs into columns

I am working with a parent div that contains 19 child divs all with the same class, structured like this: <div id="dropdown-content1"> <div class="CatsColumn"></div> <div class="CatsColumn"></div> <div class="C ...