Switch up the component's style based on the route being accessed

Is there a way to dynamically load CSS styles in a component based on URL parameters? The idea is that the user will access the page using a URL structure like SOME_URL/{screenSize}/{type}. While the component remains the same, the CSS styling should change based on these parameters. I already have a router implemented and the parameters are being captured - how can I achieve dynamic loading of CSS files for this purpose?

Below is a snippet of code, the aim is not to load a static CSS file as shown in the example, but rather load a CSS file like screen.component.21-5.a.css

    @Component({
      selector: 'app-screen',
      templateUrl: './screen.component.html',
      styleUrls: ['./screen.component.css']
    })
    export class ScreenComponent implements OnInit {


      public screenType = 'a';
      public screenSize = '21-5';

      ngOnInit() {}

      constructor(private mediaService: MediaService, private route: ActivatedRoute) {


          this.parameterSubscription = route.params.subscribe((params) => {
            if (params.size) {
              this.screenSize = params.size;
            }
            if (params.type) {
              this.screenType = params.type;
            }
          });
      }
      ...
   }

Answer №1

It is not possible to dynamically reload styles in Angular due to the requirement for style declarations to be statically analyzable for AOT compilation. When you build your application with ng build --prod, all templates and styles are compiled to JavaScript and imported ahead of time. If styles were to be reloaded based on conditionals, it would make AOT compilation impossible since the style to import would not be determinable until runtime (such as with the screenSize variable).

Instead of dynamically reloading styles, it is recommended to use ngClass to toggle between CSS classes based on the screen size.

Answer №2

To implement conditional classes, utilize ngClass

within your HTML structure

<div class="gradient "  [ngClass]="{'class-21-5': screenSize ==='21-5', 'class-a': screenType==='a'}">

...
</div>

If desired, separate the classes into different files and import them into the component.

@Component({
      selector: 'app-screen',
      templateUrl: './screen.component.html',
      styleUrls: ['./screen.component.css', './my-other-style.css']
    })

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

Dynamically adding a class name to the outer element of a component

I have implemented a custom tag using cq:htmlTag in one of my components. Instead of assigning a static class name from a CSS file to the "class" property, I need to use the 'template name' as the value for the class property. Is there a method ...

What is preventing me from connecting to dockerized npm from my host machine?

Issue - A server running inside a docker container is not responding when accessed from outside the container on an OSX host. web: image: my_web build: context: ./ dockerfile: web.docker container_name: my_web networks: ...

Extract values from a deeply nested object while retaining the type information

How can I map all object values of the first obj while preserving the generic type for the Wrapped object? I attempted this using a mapped type, but encountered two issues: I'm struggling to represent a nested Object in the MapToWrappedType I can&ap ...

Top method for showcasing animated images (HTML/CSS/JS)

For my website, I want to create an engaging animation showing a coin being flipped multiple times in the air before landing on a specific side. After the animation finishes, I would like it to transform into a static image of the final result. I've ...

How to customize font styles in AngularJS

I'm attempting to modify the font style of an element when a certain variable is true. Within my controller, I have a variable that retrieves its value. My objective is to adjust the font style depending on this value using ng-style. I've exhau ...

The type 'MockStoreEnhanced<unknown, {}>' is not compatible with the type 'IntrinsicAttributes & Pick[...]

I'm currently working on creating a unit test for a container in TypeScript. From what I've gathered from various responses, it's recommended to use a mock store and pass it to the container using the store attribute. This method seems to o ...

Why do referees attempt to access fields directly instead of using getters and setters?

I am facing an issue with my TypeScript class implementation: class FooClass { private _Id:number=0 ; private _PrCode: number =0; public get Id(): number { return this._Id; } public set Id(id: number) { this._Idprod ...

Leveraging this jQuery code across multiple div elements

As a newcomer to jQuery, I am currently experimenting with a test script. My goal is to create an effect where when an image is clicked, a div slides down displaying more information similar to the new google images effect. The issue with the current scri ...

Is there a way to determine the quantity of lines within a div using a Vue3 watcher?

Is it feasible to determine the number of text lines in a div without line breaks? I am looking to dynamically display or hide my CTA link based on whether the text is less than or equal to the -webkit-line-clamp value: SCRIPT: const isExpanded = ref(true ...

Display the toggle button for expanding/collapsing text only when the length of the string exceeds 50 characters

Is there a way to only show a "read more/less" button in a table if the content exceeds 50 characters? The table contains a mix of content, some short announcements with about 10 characters and others with over 100. <div class="col"> <span ng-c ...

Enhance filtering capabilities in FormGroup with an autocomplete input feature for more options

Seeking to implement a basic autocomplete textbox that allows selection from a filtered list of objects displayed by name. For instance, with an array of Country objects containing properties like countryName, countryCode, and countryId, the goal is to fi ...

Annoying border problem encountered with Angular material column header

After upgrading Angular Material to version 9, I encountered an issue where a bottom border appears under the sorted column heading in my mat-table. Strangely, the border disappears when clicked upon. Upon inspecting the browser's CSS, I discovered t ...

Having trouble installing npm package in Angular project

After cloning my project from GitLab, I encountered an issue while trying to install the NPM packages. When I ran npm install, an error popped up: https://i.stack.imgur.com/WNT5s.png Upon checking the log file, I found the following error message: 3060 ...

Exploring unit tests: Customizing an NGRX selector generated by entityAdapter.getSelectors()

Let's imagine a scenario where our application includes a books page. We are utilizing the following technologies: Angular, NGRX, jest. To provide some context, here are a few lines of code: The interfaces for the state of the books page: export int ...

Combining properties from one array with another in typescript: A step-by-step guide

My goal is to iterate through an array and add specific properties to another array. Here is the initial array: const data = [ { "id":"001", "name":"John Doe", "city":"New York&quo ...

Prevent Chrome Extension Pop-up from Resetting when Closed

I am completely new to the world of programming, with a special focus on web development. My current project is rather simple - it's a Chrome extension designed for note-taking purposes. This extension creates a pop-up window when the user clicks on i ...

Issue: Angular is indicating that the 'feedbackFormDirective' member is implicitly assigned with type 'any'

I am encountering an error in my project while using Angular version 12. Despite extensive research, I have been unable to find a solution. Here is my .ts file: import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { Feedba ...

Difficulty with the value binding issue on input text produced by *NgFor

When using *ngFor in Angular to loop over an array and generate input text elements bound to the values in the array, I'm encountering some issues. The value is not binding correctly when a user inputs something into the text field. I attempted to ru ...

Unable to classify mapRef.current

I am facing an issue with my react component that contains a leaflet map. TypeScript is warning me about line mapRef.current.setView(coords, 13), stating it is an "unsafe call of an any typed value" import 'leaflet/dist/leaflet.css'; import { Map ...

What could be causing the "ng not found" error as I try to deploy my Angular application on Heroku?

Here is the structure of my project: package.json (A) index.js client > package.json (B) This is how the outer package.json (A) is set up : { "name": "---", "version": "1.0.0", "description": "---", "main": "index.js", "scripts": { "sta ...