Reputation: 1009
I am trying to load css styles in a component based on the URL parameters. Basically the user will load the page like SOME_URL/{screenSize}/{type}
. This shall always load the same component, but with different CSS styling. I am already using a router and have the parameters set - how can I dynamically load the CSS files? Is that possible at all?
Here is some code - basically the goal is not to load the static CSS file defined in the example, but to load something 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;
}
});
}
...
}
Upvotes: 0
Views: 1046
Reputation: 3315
You cannot do that, as Angular requires the style declarations to be statically analyzable. This is done for the AOT compilation. All of your templates and styles are getting compiled to JavaScript when you run ng build --prod
, and the styles are imported ahead of time. So, if you could reload styles using some conditionals, that code would no longer be statically analyzable (the screenSize
variable can be known only during runtime, so which style should we import when building ahead of time?), thus resulting in the impossibility of AOT compilation.
(no, there is no way of compiling both styles and then importing them in runtime - that would mean we could understand what output will the function produce, which is virtually impossible - see halting problem)
But you can (and should) use ngClass
to toggle between css classes depending on the screen size.
Upvotes: 3
Reputation: 9392
You can use ngClass
in your html
<div class="gradient " [ngClass]="{'class-21-5': screenSize ==='21-5', 'class-a': screenType==='a'}">
...
</div>
You can put the different classes in different files and import it on the component if you want.
@Component({
selector: 'app-screen',
templateUrl: './screen.component.html',
styleUrls: ['./screen.component.css', './my-other-style.css']
})
Upvotes: 1